Before, we introduced
data types for Python,
programming problems with strings, this article we will introduce
format of the Python string
ofProblem:
So how to output a formatted string. We will often output similar ' Dear XXX Hello! You xx month's bill is XX, the balance is xx ' and so on the string, and the XXX content is varies according to the variable, therefore, needs a simple format string the way.
In Python, the format used is consistent with the C language and is implemented as a % , for example:
>>> ' Hello,%s '% ' world ' Hello, world ' >>> ' Hi,%s, you have $%d. '% (' Michael ', 1000000) ' Hi, Michael, y The OU has $1000000. '
As you may have guessed, the% operator is used to format the string. Inside the string,%s is replaced with a string,%d is replaced with an integer, there are several% placeholder, followed by a number of variables or values, the order to correspond well. If there is only one%, the parentheses can be omitted.
Common placeholders are:
Placeholder |
Replace content |
%d |
Integer |
%f |
Floating point number |
%s |
String |
%x |
hexadecimal integer
|
where formatted integers and floating- point numbers can also specify whether to complement 0 and the number of digits of integers and decimals:
#-*-Coding:utf-8-*-print ('%2d-%02d '% (3, 1)) print ('%.2f '% 3.1415926)
If you're not sure what to use,%s will always work, and it will convert any data type to a string:
>>> ' Age:%s. Gender:%s '% (+ True) ' age:25. Gender:true '
Sometimes, what happens if the% inside the string is a normal character? This time you need to escape, with a percent of%:
>>> ' growth rate:%d percent '% 7 ' growth rate:7% '
Summary
The Python 3 string uses Unicode and supports multiple languages directly.
When Str and bytes are converted to each other, the encoding needs to be specified. The most commonly used encoding is UTF-8. Python, of course, also supports other encodings, such as encoding Unicode into GB2312:
>>> ' Chinese '. Encode (' gb2312 ') B ' \xd6\xd0\xce\xc4 '
But this is a purely trouble-free way, and if there are no special business requirements, remember to use only UTF-8 encoding.
When formatting a string, you can use Python's interactive environment to test it quickly and easily.