Python String Formatting Learning notes

Source: Internet
Author: User
Tags explode php explode print format string format in python

The format of the output string in Python uses the% operator, which is common in the form

• Format tag string% value group to output
where the "format tag string" In the left part can be completely consistent with C. The ' Value group ' on the right should be enclosed in parentheses if there are two or more values, separated by a cornet in the middle. Focus on the left part. The simplest form of the left section is:


%cdoe
There are a variety of code, but because in Python everything can be converted to string type, so if there is no special requirement, it can all be marked with '%s '. Like what:


• '%s%s '% (1, 2.3, [' One ', ' two ', ' three '])
Its output is ' 1 2.3 [' One ', ' two ', ' three '] ', which is printed according to the mark on the left side of the%. Although the first and second values are not string types, there is no problem. In this process, when the computer finds that the first value is not%s, it first calls the integer function, turns the first value, 1, to string, and then calls the STR () function to output. There is also a repr () function, which can be marked with%r if you want to use this function. In addition to%s, there are a number of similar code:

String formatting:

The code is as follows Copy Code

format = "Hello%s,%s enough for ya?"
Values = (' World ', ' hot ')
Print format% values
Result: Hello world, hot enough for ya?

Note: 2.7 is OK. 3.0, No.

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

Similar to PHP but not the same function or method name:

explode/"target=" _blank ">php explode=> python split
PHP trim => python Strip
PHP implode => python join

The Unicodedecodeerror exception was encountered while formatting strings in the work, so the knowledge of string formatting was studied and shared.

  code is as follows copy code

C: Userszhuangyan>python
Python 2.7.2 (default, June, 15:08:59) [MSC v.1500 bit (Intel)] on win

Type ' help ', ' copyright ', ' credits ' or ' license ' for the more information.
>>> a = ' Hello World '
>>> print ' Say this:%s '% a
Say this: Hello World
>>> print ' Say th Is:%s and say that:%s '% (A, ' Hello World ')
say this: Hello Worlds and say That:hello worldwide
>>> print ' Say t His:%s and say this:%s '% (A, u ' Hello World ')  
Traceback (most recent called last):
  File "<stdin& gt; ", line 1, in <module>
Unicodedecodeerror: ' ASCII ' codec can ' t decode byte 0xc4 in position 10:ordinal
 not in range (128)


See print ' Say this:%s and Say that:%s '% (A, u ' Hello World ') is this quote unicodedecodeerror wrong, and the difference between the last sentence is to change ' Hello World ' to u ' Hello World ' cause, the Str object becomes a Unicode object. But the question is, ' Hello World ' is simply an English string that does not contain any characters other than ASCII, how can it be decode? Take a closer look at the message that came with the exception, which mentioned 0xe4, which is obviously not ' Hello World ', so you can only doubt that Chinese sentence.

>>> a ' Xc4xe3xbaxc3xcaxc0xbdxe7 '

The byte sequence of its print out, sure enough is it, the first is 0xe4.

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

The code is as follows Copy Code

>>> ' Say this:%s '% ' Hello '
' Say This:hello '
>>> ' Say this:%s '% u ' Hello '
U ' Say this:hello '
>>>

Look carefully, ' hello ' is an ordinary string, the result is a string (str object), u ' Hello ' becomes a Unicode object, and the formatted result becomes Unicode (note the U at the beginning of the result).

Look at what the Python document says:

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

If the code is mixed with STR and Unicode, this problem is easy to come by. In the colleague's code, the Chinese string is the user input, after the correct coding processing, is the UTF-8 encoded STR object; But the mess of the Unicode object, although its contents are ASCII, is derived from the results of the Sqlite3 database query, The strings returned by the SQLite API are Unicode objects, so the result is so bizarre.

Finally I test the format format string in the way no such exception occurs!

The code is as follows Copy Code

>>> print ' Say this:{0} and Say that:{1} '. Format (a,u ' Hello World ')
Say this: Hello World and Say That:hello

Next we'll look at the basic usage of format.

The code is as follows Copy Code
>>> ' {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 demo under 2.x, and the format method in 3.x has more powerful features

Like the sprintf function in C, you can format a string with "%".

Table 3.1. String Format Code

format Description
% percent sign
% c character and ASCII code
%s string
%d signed integer (decimal)
%u unsigned integer (10 System
%o unsigned integer (octal)
%x unsigned integer (hexadecimal)
% X unsigned integer (16 uppercase characters)
% e floating point number (scientific notation)
% E floating-point numbers (scientific notation, substituting E for e)
%f floating-point number (with decimal point symbol)
%g floating-point number (using%e or%f depending on the size of the value)
% G floating-point number (similar to%G)
%p pointer (memory address that prints values in hexadecimal)
%n stores the number of output characters in the next variable in the argument list
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.