There are two ways to format a Python string, one is in the format string "%", the other is the Format function formatting, the latter how to use I do not know.
Formatting action Symbols
There are several general formatting operators:
%c converted to character (ASCII value, or string of length one)
%r takes precedence over string conversions with the repr () function
%s takes precedence over string conversion with the STR () function
%d/%i turns into signed decimal number
%u turns into unsigned decimal number
%o Turn unsigned octal number
%x/%x turns to unsigned hexadecimal number (x/x represents the case of the converted hexadecimal character)
%e/%e turns into scientific notation (e/e control output e/e)
%f/%f to floating point (fractional part natural truncation)
%g/%g%e and%f/%e and%f abbreviations
Percent output% (the formatted string includes a percent semicolon, so you must use a percentile)
In addition to the format operator, we need to use the Format Operator helper in the process of using string formatting
The General Format operator Helper is as follows:
* Define width or decimal point accuracy
-Used for left alignment
+ Show plus sign (+) in front of positive number
# 0 (0) in front of octal number, "0x" or "0X" before hexadecimal (depending on "x" or "X")
0 The number displayed is preceded by "0" instead of the default space
(Var) mapping variables (typically used to process parameters of a field type)
M.N m is the smallest total width displayed, and n is the number of digits after the decimal point (if available)
I'm familiar with it. Three%s%d%f
Simple conversion Case:
1; #简单转换, the following format character D option is used to format an integer, and if I convert a value here that deals with an integer, an error will be made, such as a string
SS = ' Price of eggs:$%d '% 42
Print (ss)
# #运行结果如下
Price of eggs:$42
2. Add a String
SS = ' Price of eggs:$%d '% "greatly large"
Print (ss)
# #报错信息如下:
Traceback (most recent):
File "d:/pythontest/mypython/day1/str.py", line 5, <module>
SS = ' Price of eggs:$%d '% "greatly large"
TypeError:%d format:a number is required, not str
The rest will be understood later.
This article is from "think one or two" blog, please be sure to keep this source http://250919938.blog.51cto.com/962010/1905707
Python string formatting