String formatting
Python supports the output of formatted strings. Although this may use very complex expressions, the most basic usage is to insert a value into a string with the string format character% s. In Python, string formatting uses the same syntax as the sprintf function in C.
The general format for formatting output strings in Python is:
Format tag string% Value group to be output
Among them, the "format mark string" on the left can be exactly the same as in c. If there are two or more values in the "value group" on the right, they need to be enclosed in parentheses and separated by commas.
Focus on the left part. The simplest form of the left part is:
% code
There are many kinds of codes, but in Python, everything can be converted to string type, so if there are no special requirements, you can use ‘% s’ to mark them all. such as:
‘% S% 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 type string, 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, convert the first value, which is 1, into the string type, and then call the str () function to output. As mentioned earlier, there is also a repr () function. If you want to use this function, you can use% r to mark it. In addition to% s, there are many similar codes:
Integer:% d
Unsigned integer:% u
Octal:% o
Hexadecimal:% x% X
Floating point:% f
Scientific notation:% e% E
Automatically select% e or% f according to different values:% g
Automatically select% E or% f according to different values:% G
Just like using the \ to escape, the% is used as the format mark, and there is also a question of how% should be output. If you want to output% itself in the "format mark string", you can use %% to represent it.
The above is just the simplest form of formatting. Let's look at a bit more complicated:
‘% 6.2f’% 1.235
In this form, a decimal 6.2 appears in front of f, which means that the total length of the output is 6 characters, including 2 decimal places. There are more complicated ones:
‘% 06.2f’% 1.235
There is a 0 before the 6 to indicate that if the number of output digits is less than 6 digits, the 6 digits will be complemented by 0. The output of this line is ‘001.24’, and you can see that the decimal also occupies one digit. Markers like 0 here also have-, +. Among them,-means left-aligned, + means plus sign in front of positive numbers, the default is not added. Finally, look at the most complex form:
‘% (Name) s:% (score) 06.1f’% {‘score‘: 9.5, ‘name‘: ‘newsim’}
This form is only used when the content to be output is a dictionary (a Python data type), and the (name) and (score) in parentheses correspond to the keys in the subsequent key-value pairs. As you can see in the previous example, the order of the marks in the "format mark string" corresponds to the values in the "value group to be output". There is a sequence, one-to-one, two-to-two. In this form, it is not. Which value corresponds to each format tag is specified by the key in parentheses. The output of this line of code is: ‘newsim: 0009.5’.
Sometimes in the form of% 6.2f, 6 and 2 can not be specified in advance, and will be generated during the running of the program, so how to enter it, of course, you cannot use %% d.% Df or% d.% D% f . You can use the form of% *. * F, of course, the "value group to be output" in the back contains those two * values. For example: ‘% *. * F’% (6, 2, 2.345) is equivalent to ‘% 6.2f’% 2.345.
This is the most complicated content of this book so far. However, if you ca n’t remember, or do n’t want to be so patient, you can use% s instead, or use multiple "+" to construct a similar output string. The% here is a bit of a division, no wonder the designer will choose to use the% division sign.
The string formatting code is as follows:
%% percent sign
% c character and its ASCII code
% s string
% d signed integer (decimal)
% u unsigned integer (decimal)
% o unsigned integer (octal)
% x unsigned integer (hexadecimal)
% X unsigned integer (hexadecimal uppercase characters)
% e floating point number (scientific notation)
% E floating point number (scientific notation, use E instead of 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 of the value printed in hexadecimal)
% n stores the number of output characters and puts it in the next variable in the parameter list
Examples of string related operations
# String alignment
word = "version3.0"
# 20 characters aligned in the middle
print word.center (20)
# 20 characters filled on both sides *
print word.center (20, "*")
# Align left
print word.ljust (0)
# 20 characters right aligned
print word.rjust (20)
# 20 characters left in front
print "% 30s"% word
#Remove escape characters
strip ()
lstrip ()
rstrip ()
#Character segmentation
split ()
split (",")
split (",", 2)
#String comparison
startswith ()
endswith ()
#Find and replace
find (substring [, start [, end]])
rfind ()
replace (new, old [, max])
#String and date
time.strftime (format [, tuple])-> string
time.strptime (string, format)-> struct_time
String formatting
>>> k = "uid"
>>> v = "sa"
>>> "% s =% s"% (k, v)
‘Uid = sa’ The value of the entire expression is a string. The first% s is replaced by the value of the variable k; the second% s is replaced by the value of v. All other characters in the Python formatted string (in this case, the equal sign) are printed out as is. Note that (k, v) is a tuple. String formatting is more than just concatenation. It's not even just formatting. It is also mandatory type conversion.
Comparison of string formatting and string concatenation
>>> uid = "sa"
>>> pwd = "secret"
>>> print pwd + "is not a good password for" + uid
secret is not a good password for sa
>>> print "% s is not a good password for% s"% (pwd, uid)
secret is not a good password for sa
>>> userCount = 6
>>> print "Users connected:% d"% (userCount,)
Users connected: 6
>>> print "Users connected:" + userCount
Traceback (innermost last):
File "<interactive input>", line 1, in?
TypeError: cannot concatenate ‘str’ and ‘int’ objects
The article is reproduced from: [169IT-the latest and most complete IT information]
Title of this article: Python string formatted output and related operation code examples