string of 5.python

Source: Internet
Author: User
Tags string format

The word "string" was mentioned earlier, and now it is time to learn what a string is.

First, the string is the python built-in data type, which is characterized by quotation marks, and can be single quotation marks (' string '), double quotes ("string"), three quotation marks ("' String '" and "" "" string ""). Note that these symbols are half-width symbols and are quoted in English, that is, they cannot be quoted in the Chinese input method.

When these strings are used alone and are a single line , there is no difference, for example:

' 123 '  "123" ' 123  '  "" "123 " ""

These four kinds of writing is a meaning, in addition, note that the quotation marks are caused by the string type, even if the inside is a number or other data type. Therefore, when adding to the string, the result is not the mathematical addition, but the concatenation of the string.

As shown above, but generally we do not do the concatenation of strings, because the stitching method here is very inefficient, wasting memory space. For example:

' 123 ' ' 456 '

In this case, ' 123' is created in memory, then '456' is created and then stitched into ' 123456 ' And then put it in memory, and then use the variable to point to the value in memory. We created two additional values in this process, and this extra value is what we don't need. If a lot of splicing, it will certainly produce a lot of useless data, not only waste memory, but also trigger the Python garbage collection mechanism, and Python in the garbage collection, is not doing other things, so that our code efficiency is very low.

1. Concatenation of strings

In addition to using the + number for stitching, but also 2 ways to achieve splicing ( in fact, there is a use of + = symbol of the stitching method, and seemingly efficient, but I also look at other people's articles to see, the individual is not too clear principle, So I won't say it.)

1. ' Io. Stringio ', memory string IO stitching (operating from the memory level, with little or no understanding, here is not much explanation)

2.str.join (), using the string's join () method (str is the class that creates the string object, which is explained in detail in the object-oriented way, see the Code demo first)

"'      # first create an empty string, which is called object-oriented to create the object a.join ('ABC', ' def ')    # use Join () method to stitch a string, and the Join () method inherits from the parent class

Here added from the object-oriented interpretation, if not understand, you can study after the object-oriented back, I was learning at the time is a face, but after the object-oriented, I have a sense of epiphany, I will share my understanding of object-oriented.

To summarize its usage:

1. Start with a string object that is created by the Python built-in class of STR, otherwise there is no join () .

2. The syntax format is str.join (sequence) , where sequence represents a sequence with six built-in sequences in Python: list, tuple, string, Unicode string, The buffer object and the Xrange object (summarized later).

That is, in addition to passing a meta-ancestor as an example, it is possible to pass a string, so can it be written like this:

"' b.join ('123','456')

The answer is no, there will be an error, the error message is as follows:

Specifically, the function as long as a data, we gave two, so the error.

That is, when we write this, we actually pass two sequences in, a string is a sequence.

So, what if we just pass a string?

It seems that there is no problem, when B is not empty time?

This is not the same as we imagined, not directly splicing in the last side. Obviously this is not what we want ( hang dad This is ), if it is Ganso?

(Note thatjoin () does not change the value of B, just returns a new object, about which the return value will be spoken in the function)

Well, it's a big hole, too.

  It appears that after the incoming sequence, the original string is inserted between these values by the values that are fetched by the index.

Coach, this is not the same as the deal!

In fact, we have a better approach, that is, the format of the string.

2. Formatting of strings

The principle of string formatting is that I first occupy a hole in it, but I do not fill in the pit, until the time to use, in the things to fill in.

Look at the code example first:

' Scolia '  '%s is a handsome guy ' %nameprint A

Scolia uses the string format, the effect tension pile, scolia got the ' handsome ' title.

The inside of the %s is called the pit, and the outside of the %name is what we want to fill in the things, of course, we usually use variables to store this value, if you interact with the user to dynamically change the value of name, Then everyone can be ' handsome '.

But then we are not satisfied, if the user is female? It's not appropriate to use a handsome guy. At this time, we can occupy a few more pits.

' Scolia '  '  handsome'%s is a%s' %(name,how) Print A

Results:

No problem, more than a few pits can also, but a little change in writing (changed to the form of the Yuan Zu, Ganso in detail later will speak), this time you can think how to change how to change ( to the beauty herself to write ).

Theoretically with a few placeholders can be, as long as there is a corresponding variable (the number of variables and placeholders should be incorrect ), and in order to replace the inside placeholder.

But what if we don't want to pass it in order? It can be written like this:

' % (name) s is a percent (how) s' %{' How':' handsome ','  name':'scolia'}

The result is the same as above, the value is passed in a dictionary, and then the dictionary key is used to get it, the details of the dictionary will be spoken later.

At this point, some people will ask what is the meaning of s in %s ( you should ask, do not spit ), here S for I will use a string to fill the hole, similar, we can also have the following wording:

tr>
Format description
%s string
%r string (r EPR ()
%d signed integer (decimal)
%u unsigned integer (decimal)
%o unsigned integer (octal)
%x unsigned integer (hex)
% x unsigned integer (16 uppercase characters)
% e Floating-point number (scientific notation)
% e Floating-point number (scientific notation, E instead of e)
%f floating point number (with decimal point symbol)
%g Floating-point number (%e or%f depending on the size of the value)
% G floating point number (similar to%G)
%p pointer (memory address to print values in hexadecimal)
%n stores the number of output characters placed in the next variable in the parameter list
% c character and its ASCII code
% character '% '

This is the watch I found on the Internet. Many types, is not what I use to replace, it is necessary to use what placeholder ah, so much so remember to live?

First of all, these things are controlled in the format of the display . and, in many cases, a %s is sufficient, because when using this tag, the incoming data is first converted to a string using the str () method. All of Python's data types can be converted to strings (as others write), and the result is a string (otherwise, the format of the string). Anyway, most of the use is no problem.

Therefore, the format of the placeholder can be summarized as:

%[(name)][flags][width]. [Precision]typecode

[] Delegates are optional, which is indicated later.

(name): Use the dictionary key to pass the value, the above mentioned

TypeCode: Data type, also in the table above, the general%s is sufficient, of course, there is a need to use other.

Flags: can have +,-, ' or 0. + indicates align to the right. -Indicates aligned to the left. ' is a space, 0 means 0 padding.

Width: Indicates the width of the display, after the width is set, the various alignments above, the fill has effect.

What do these alignments, fills, and widths mean? First of all, I have a string ' scolia ', the length of 6, but I hard to use 10 characters to display the length of what to do, that is not more than 4 positions, this 4 position how to do, is not can be filled with space or 0. But these 4 more than the length of the position is not sure, then I can let the original character to occupy the position, is so-called alignment, the remaining position after alignment is the location of the fill.

Precision: Indicates the precision after the decimal point, used with floating point numbers.

 Of course, there are other ways of formatting strings, and this is not going to go any further.

3. Nesting of quotation marks

As I said at the beginning, when several quotation marks are used alone and only one row, the effect is the same. But when it comes to nesting, there are a few things to watch out for, as shown in the following example:

' Scolia says: ' I want to say a word '  #错误写法

This time, will cause confusion, like here color logo, the front of the paragraph as a string, and the latter paragraph is not in line with the grammar, it will definitely error.

So, this is how it's going to be written.

' Scolia said: \ ' I want to say a word ' '
A

where \ is the escape symbol, where the meaningful quotation marks (') are converted to ordinary symbols, which are escaped and lose the meaning of the string.

The result is what we want, but it's too much trouble to escape every time, and we can do this.

" Scolia said: ' I want to say a word ' "
A

Use double quotes around the perimeter, using single quotes in it, so that the single quotes inside will not be interpreted to create a string.

Of course, upside down is also possible:

' Scolia said, "I want to say a word." ' Print A

The result is the same.

But sometimes we have the need to:

' Scolia said: "I want to say a word, this sentence is a long long long long long long long long long long long long long length long long length" ' Print A

The result is this:

But this sentence is too long, I have to carry on the line to do so?

That's the way to write:

' Scolia said: "I want to say a word, this sentence is very long and long long long long long long, long and long length long length" ' Print A

The result is this:

in which, \ n means a newline character (of course, the \ also escape character, but the original meaningless characters into a meaningful), here will be a line, but also a lot of special characters, here not one by one enumerated.

But every time you change the line to use \ \ is too much trouble, I write when you can change it?

Obviously my IDE uses a wavy red line to indicate that this is a grammatical error.

I'll write it that way.

The \ symbol indicates that my line of code cannot be written, and I want to change the line and then write (this symbol is the same as in the Linux command), the result is:

Well...... A few more spaces, then I'll change:

Run it:

Well, the space is gone, however, and there is no egg to use.

Unwilling to heart ah, there is no solution? At this point, three quotes indicate: child, you are too young.

" "  Scolia said: "I want to say a word, this sentence a long long long long long long long long long                long long long long long long long long long long long long long long long length of long Long" "'" ' Print a

It is also important to note the nested problem of single and double quotes.

A look at the results of the operation, unexpectedly, this is true magic.

At this time, the witty person said, three quotation marks is not a multiline notation of the comment? Why this can be used as a special symbol to create strings, so confusing!

In fact, it is a good way to tell whether a three quotation mark is written in the end of a comment or a string, that is, to see if it is preceded by an assignment to a variable, see the standard assignment symbol (=). If there is an assignment, it is creating a string object, no, that is the comment.

  It's so witty, like me, I've found it all.

Well, the question of quotation marks is here first.

4. Sequence characteristics of strings

All say that the string is also a sequence, then you can use a sequence of methods to deal with it.

All sequence types can perform certain operations. These actions include: index (Indexing), Shard (sliceing), add (adding), multiply (multiplying), and check whether an element belongs to a member of a sequence (membership). In addition, Python has built-in functions for calculating the length of a sequence, finding the largest and smallest elements.

About the sequence, later will be a separate article to explain, anxious words can see how others write first, or you see I updated the content of the back.

5. Built-in methods of strings

These methods are a bunch of people who may learn to memorize, but I suggest that after learning to look at objects and then review them, there will be a sense of epiphany.

The summary of the built-in method also has another explanation, because it is too long and long to write here.

Let me have a rest ...

string of 5.python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.