Python string formatting study notes, python Study Notes

Source: Internet
Author: User
Tags php explode print format

Python string formatting study notes, python Study Notes

In python, the % operator is used to format the output string. The common format is

• Mark the string % value group to be output in the format
The "format mark string" on the Left can be exactly the same as that in c. If there are two or more values in the 'value Group' on the right, they must be enclosed in parentheses and separated by short signs. Focus on the left part. The simplest form of the left part is:


• % Cdoe
There are many types of codes, but in python, everything can be converted to the string type. Therefore, if there are no special requirements, you can use '% s' to mark them all. For example:


• '% S % s' % (1, 2.3, ['one', 'two', 'three'])
Its output is '1 2.3 ['one', 'two', 'three] ', which is output according to the mark on the left of %. Although the first and second values are not of the string type, there is no problem. In this process, when the computer finds that the first value is not % s, it will first call the integer function to convert the first value, that is, 1, to the string type, then, call the str () function to output the data. As mentioned above, there is also a repr () function. If you want to use this function, you can mark it with % r. In addition to % s, there are many similar codes:

String formatting:

The Code is 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 is acceptable. Not 3.0

3.0 use print (format % values) in parentheses.

Similar to php but with different function or method names:

Explode/"target =" _ blank "> php explode => python split
Php trim => python strip
Php implode => python join

The UnicodeDecodeError error is encountered when formatting a string at work. Therefore, you can share your knowledge about string formatting.

The Code is as follows:
C: Userszhuangyan> python
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> A = 'Hello world'
>>> Print 'say this: % s' %
Say this: Hello World
>>> Print 'say this: % s and Say that: % s' % (a, 'Hello World ')
Say this: hello world and say that: hello world
>>> Print 'say this: % s and Say that: % s' % (a, u 'Hello World ')
Traceback (most recent call last ):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii 'codec can't decode byte 0xc4 in position 10: ordinal
Not in range (128)


Have you seen the UnicodeDecodeError reported by print 'say this: % s and Say that: % s' % (a, u 'Hello World, the difference between the str object and the preceding sentence is that 'Hello world' is changed to u'hello world', And the str object is changed to a unicode object. But the problem is that 'Hello world' is only an English string that does not contain any characters other than ASCII. How can it be decode (www.111cn.net )? Take a closer look at the message that comes with the exception. 0xe4 is mentioned in it. This is obviously not in 'Hello world', so you can only doubt the Chinese sentence.

>>> A' xc4xe3xbaxc3xcaxc0xbdxe7'

Print out its byte sequence. The first one is 0xe4.

It seems that Python tries to convert a decode into a unicode object during string formatting, and decode uses the default ASCII encoding instead of the actual UTF-8 encoding. So what is the problem ?? Next we will continue our experiment:

The Code is as follows:
>>> 'Say this: % s' % 'hello'
'Say this: hello'
>>> 'Say this: % s' % u'hello'
U'say this: hello'
>>>

Take a closer look, 'Hello' is a common string, and the result is also a string (str object). u'hello' becomes a unicode object, the formatted result is also unicode (note the u at the beginning of the result ).

Let's take a look at what the Python documentation says:

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

If str and unicode are mixed in the code, this issue is very likely to occur. In my colleagues' code, the Chinese string is the str object that the user inputs, which is encoded in UTF-8 after correct encoding; but the troublesome unicode object, although its content is all ASCII code, its source is the query result of the sqlite3 database, while the strings returned by the sqlite API are unicode objects, resulting in such a weird result.

Finally, I tested that the format-format string method will not encounter the above exception!

The Code is as follows:
>>> Print 'say this: {0} and Say that: {1} '. format (a, u 'Hello World ')
Say this: hello world and say that: hello world

Next we will study the basic usage of format.

The Code is as follows:
>>> '{0}, {1}, {2}'. format ('A', 'B', 'C ')
'A, B, C'
>>> '{2}, {1}, {0}'. format ('A', 'B', 'C ')
'C, B,'
>>> '{2}, {1}, {0}'. format (* 'abc') # unpacking argument sequence
'C, B,'
>>> '{0} {1} {0}'. format ('aba', 'cad ') # arguments 'indices can be repeated
'Abracadaba'
>>> 'Coordinates: {latitude}, {longdegree} '. format (latitude = '37. 24n', longpolling ='-115.81w ')
'Coordinates: 37.24N,-115.81W'
>>> Coord = {'latitude ': '37. 24n', 'longyun':'-115.81W '}
>>> 'Coordinates: {latitude}, {longdegree} '. 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 in 2. x. The format method in 3. x has more powerful functions.

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


Format python strings

In python, the output tag is similar to the printf () format in c. In python, the % operator is used to format the output string. The common format is
Format mark string % value group to be output
The "format mark string" on the Left can be exactly the same as that in c. If there are two or more values in the 'value Group' on the right, they must be enclosed in parentheses and separated by short signs. Focus on the left part. The simplest form of the left part is:
% Cdoe
There are many types of codes, but in python, everything can be converted to the string type. Therefore, if there are no special requirements, you can use '% s' to mark them all. For example:
'% S % s' % (1, 2.3, ['one', 'two', 'three'])
Its output is '1 2.3 ['one', 'two', 'three] ', which is output according to the mark on the left of %. Although the first and second values are not of the string type, there is no problem. In this process, when the computer finds that the first value is not % s, it will first call the integer function to convert the first value, that is, 1, to the string type, then, call the str () function to output the data. As mentioned above, there is also a repr () function. If you want to use this function, you can mark it with % r. In addition to % s, there are many similar codes:
Integer: % d
Unsigned integer: % u
Octal: % o
Hexadecimal: % x % X
Floating Point: % f
Scientific Note: % e % E
Automatically select % e or % f: % g based on different values
Automatically select % E or % f: % G based on different values
As mentioned above, escape with "\" is the same. Here, % is used as the mark of the format, and there is also a question about how % should be output. If you want to output % itself in the format mark string, % can be used.
The above is just the simplest form of format mark. It is more complex:
'% 6.2f' % 1.235
In this form, a decimal point 6.2 is displayed before f, which indicates that the total output length is 6 characters, with two decimal places. More complex:
'% 06.2f' % 1.235
A value of 0 is added before 6, indicating that if the number of output digits is less than 6, 0 is used to make up 6 digits. The output of this row is '001. 24'. It can be seen that the decimal point also occupies one place. Tags similar to 0 include-and +. -Indicates the left alignment, and + indicates that the plus sign is also placed before the positive number. By default, the plus sign is not added. Finally, let's look at the most complex form:
'% (Name) s: % (score) 06.1f' % {'score': 9.5, 'name': 'newsim '}
In this form, only when the output content is dictionary (a python data type), the (name) and (score) in parentheses correspond to the keys in the subsequent key-value pairs. In the previous example, we can see that the order marked in the "format mark string" and the values in the "value group to be output" are one-to-one, ordered, one-to-one, and two-to-two. In this form, no value corresponding to each format mark is specified by the key in parentheses. The output of this line of code is: 'newsim: 808080 '.
 
Sometimes in the form of % 6.2f, 6 and 2 cannot be specified in advance and will be generated during the program running. How can we input this? Of course, % d cannot be used. % df or % d. % d % f. It can be in the form of % *. * f. Of course, the following "value group to be output" contains the two * values. For example, '% *. * F' % (6, 2, 2.345) is equivalent to' % 6.2f '% 2.345.
This is the most complex content this book has ever seen. However, if you cannot remember, or... the remaining full text>

Python string formatting

In %. 3f, % indicates the symbol behind the boot, which is used to format the variable % after the string into a string.
. 3 indicates that three digits are retained after the decimal point. F: format the variable to be formatted as a floating point.
In format % pi, % indicates to convert pi to string and replace %. 3f in format according to the requirements of %. 3f in format.

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.