Python String Formatting Learning notes

Source: Internet
Author: User
Tags php explode print format

Formatting the output string in Python uses the% operator, which is a common form of

• Format tag string% value group to output
The "format tag string" In the left part can be exactly the same as in C. The right ' value group ' if there are two or more values, you need to enclose them in parentheses, separated by a cornet. Let's focus on the left part. The simplest form of the left part is:


%cdoe
There are a number of code in it, but since in Python everything can be converted to a string type, there is no special need to use '%s ' entirely to mark it. Like what:


• '%s%s '% (1, 2.3, [' One ', ' both ', ' three ')
Its output is ' 1 2.3 [' One ', ' one ', ' one ', ' three '] ', which is output according to the mark on the left of the%. Although the first and second values are not of type string, they are not a problem. In this process, when the computer discovers that the first value is not%s, the function of the integer number is called First, the first value is 1 to the string type, and then the STR () function is called to output. As I said before, there is a repr () function, which can be tagged with%r if you want to use this function. In addition to%s, there are a number of similar code:

String formatting:

Code to copy code as follows
format = "Hello%s,%s enough for ya?"
Values = (' World ', ' hot ')
Print format% values
Result: Hello world, hot enough for ya?

Note: 2.7 Yes. 3.0 No.

3.0 use print (format% values) to enclose it in parentheses.

A place similar to PHP but with a different function or method name:

explode/"target=" _blank ">php explode=> python split
PHP trim = python strip
PHP implode = python Join

Working in the format of the string encountered a Unicodedecodeerror exception, so the study of string formatting related knowledge and everyone share.

The

Code copies the code as follows
C:userszhuangyan>python
Python 2.7.2 (default, June, 15:08:59) [MSC v.1500 (Intel)] On Win
+
Type "help", "copyright", "credits" or "license" for more information.
>>> a = ' Hello World '
>>> print ' Say this:%s '% a
Say this: Hello World
>>> print ' Say this: %s and say that:%s '% (A, ' Hello Worlds ')
say this: Hello World and say That:hello earth
>>> print ' say this:% s and say that:%s '% (A, u ' Hello World ')
Traceback (most recent):
File "<stdin>", line 1, in < ;module>
Unicodedecodeerror: ' ASCII ' codec can ' t decode byte 0xc4 in position 10:ordinal
not in range


See print ' Say this:%s and Say that:%s ' percent (A, U ' Hello World ') The unicodedecodeerror of this quote is wrong, and the difference is just to change ' Hello World ' to u ' Hello World ' cause, the Str object becomes a Unicode object. But the problem is, ' Hello World ' is just a simple English string that doesn't contain any characters other than ASCII, how can it be decode (www.111cn.net)? Take a closer look at the message attached to the exception, which mentions 0xe4, which is obviously not ' Hello World ', so you can only doubt the Chinese.

>>> a ' Xc4xe3xbaxc3xcaxc0xbdxe7 '

It's a sequence of bytes printed out, sure enough it is, the first one is 0xe4.

It seems that Python attempts to decode a into a Unicode object when the string is formatted, and decode the default ASCII encoding rather than the actual UTF-8 encoding. So what's going on here?? Continue with our experiment below:

Code to copy code as follows
>>> ' Say this:%s '% ' Hello '
' Say This:hello '
>>> ' Say this:%s '% u ' Hello '
U ' Say this:hello '
>>>

Look closely, ' hello ' is a normal string, the result is also a string (str object), u ' Hello ' becomes a Unicode object, the formatted result becomes Unicode (note the beginning of the result of the U).

See what the Python documentation says:

If format is a Unicode object, or if any of the objects being converted using the%s conversion is Unicode objects, the R Esult would also be a Unicode object.

If the code is mixed with STR and Unicode, this problem can be easily seen. In the colleague's code, the Chinese string is the user input, after the correct encoding processing, is the UTF-8 encoded STR object; But that troubled Unicode object, though its contents are ASCII, is derived from the results of the Sqlite3 database query. The strings returned by the SQLite API are Unicode objects, which results in this bizarre result.

Finally I tested the format string in the same way without any of the above exceptions!

Code to copy code as follows
>>> print ' Say this:{0} and Say that:{1} '. Format (a,u ' Hello World ')
Say this: Hello World and Say That:hello

Next we look at the basic usage of format.

Code to copy code as follows
>>> ' {0}, {1}, {2} '. Format (' A ', ' B ', ' C ')
' A, B, C '
>>> ' {2}, {1}, {0} '. Format (' A ', ' B ', ' C ')
' C, B, a '
>>> ' {2}, {1}, {0} '. Format (* ' abc ') # Unpacking argument sequence
' C, B, a '
>>> ' {0}{1}{0} '. Format (' Abra ', ' CAD ') # arguments ' indices can be repeated
' Abracadabra '
>>> ' coordinates: {latitude}, {longitude} '. Format (latitude= ' 37.24N ', longitude= ' -115.81w ')
' coordinates:37.24n, -115.81w '
>>> coord = {' Latitude ': ' 37.24N ', ' Longitude ': ' -115.81w '}
>>> ' coordinates: {latitude}, {longitude} '. Format (**coord)
' coordinates:37.24n, -115.81w '
>>> coord = (3, 5)
>>> ' X: {0[0]}; Y: {0[1]} '. Format (coord)
' X:3; Y:5 '

The above is a demonstration under 2.x, and the format method has more powerful functions in 3.x.

Like the sprintf function in C, you can use "%" to format a string
From:http://www.111cn.net/phper/python/52545.htm

Python String Formatting Learning notes

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.