Python string formatting teaches you to print correctly: D

Use format characters%

Insert picture description here

    The% operator is used to format strings. Within the string, %s means to replace with a string, %d means to replace with an integer, there are several %? placeholders, followed by several variables or values, and the order should be one-to-one correspondence. If there is only one %?, the parentheses can be omitted. Use %% to represent a%

Lift chestnuts

>>> print('%s'%'hello world')
hello world
>>> print('%s%s'%('hello','hi'))
hellohi
>>> print('%s,%s'%('hello','hi'))
hello,hi

Sub-data type description

String

%sDirectly output the string
%20sright-aligned, take 20 digits, if it is not enough, the complement is
%-20sleft-aligned, take 20, if it is not enough, the complement will
%.2sintercept a 2-digit string
%20.2s20-digit placeholder, and intercept a 2-digit string

>>> print('%s' % 'hello world')
hello world
>>> print('%20s' % 'hello world')
         hello world
>>> print('%-20s' % 'hello world')
hello world         
>>> print('%020s' % 'hello world')
         hello world
>>> print('%.2s' % 'hello world')
he
>>> print('%20.2s' % 'hello world')
                  he
>>> print('%-20.2s' % 'hello world')
he                  
>>> 

Integer

%oOctal
%ddecimal
%xhexadecimal hexadecimal is
%10dright-justified, take 10 digits, if it is not enough, it will be
%-10dleft-justified, take 10 digits, if it is not enough, it will be
%010dright-justified, take 10 digits, if it is not enough, then it will be
%-010dleft-justified, take 10 digits, or if it is not enough, it will be 0 (0 is not displayed)
%+010dRight-aligned, display a positive sign, take 10 digits, if it is not enough, add 0 to
%-+010dleft-align, display a positive sign, take 10 digits, and fill with 0 (0 is not displayed)

>>> print('%d'% 1234)
1234
>>> print('%o'% 1234)
2322
>>> print('%x'% 1234)
4d2
>>> print('%10d'% 1234)
      1234
>>> print('%-10d'% 1234)
1234      
>>> print('%010d'% 1234)
0000001234
>>> print('%-010d'% 1234)
1234 
>>> print('%-+010d'% 1234)
+1234     
>>> print('%+010d'% 1234)
+000001234
>>> print('%-+010.5d'% 1234)
+01234    
>>> print('%-+010.6d'% 1234)
+001234   
>>> print('%+010.6d'% 1234)
+000001234

Floating point

%fKeep six significant digits after the decimal point,
%.3fretain 3 decimal places,
%eretain the six significant digits after the decimal point, and
%.3eretain 3 decimal places for exponential output , use scientific notation
%gon the premise of ensuring six significant digits, use the decimal method, otherwise use scientific Counting method
%.3gretains 3 significant digits, using decimal or scientific notation

>>> print('%f' % 1.11)          # 默认保留6位小数
1.110000
>>> print('%.1f' % 1.11)        # 取1位小数
1.1
>>> print('%e' % 1.11)          # 默认6位小数,用科学计数法
1.110000e+00
>>> print('%.3e' % 1.11)        # 取3位小数,用科学计数法
1.110e+00
>>> print('%g' % 1111.1111)     # 默认6位有效数字
1111.11
>>> print('%.7g' % 1111.1111)   # 取7位有效数字
1111.111
>>> print('%.2g' % 1111.1111)   # 取2位有效数字,自动转换为科学计数法
1.1e+03

format

formatWhat the method does is replace the parameter value to the place where the format is located

print('{} was {} years old when he wrote this book'.format(name, age))
  1. Without number, {}
  2. With digital number, the order can be changed {1}, {2}
  3. With keywords, {a}, {b}
>>> print('{} was {} years old when he wrote this book'.format('name', 'age'))
name was age years old when he wrote this book
>>> print('{0} was {1} years old when he wrote this book'.format('name', 'age'))
name was age years old when he wrote this book
>>> print('{1} was {0} years old when he wrote this book'.format('name', 'age'))
age was name years old when he wrote this book

There can also be more detailed formats

# 对于浮点数 '0.333' 保留小数点(.)后三位
print('{0:.3f}'.format(1.0/3))
# 使用下划线填充文本,并保持文字处于中间位置
# 使用 (^) 定义 '___hello___'字符串长度为 11
print('{0:_^11}'.format('hello'))
# 基于关键词输出 'Swaroop wrote A Byte of Python'  
print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))

Insert picture description here
In addition to the parameter sequence number, the template string slot can also include format control information {<参数序号>: <格式控制标记>}

The format control tag includes: <填充><对齐><宽度>,<.精度><类型>6 fields.

Insert picture description here
<宽度>Refers to the set output width of the current slot.
If the actual format()width of the actual parameter is larger than the setting <宽度>, use the actual length of the
parameter. If the actual width of the parameter is smaller than the setting <宽度>, the extra digits will be filled with spaces by default, and the filling symbol can also be set

>>> print("{0:*>30}".format('hello'))   # 30个字符,右对齐,左边补空格
*************************hello
>>> print("{0:*^30}".format('hello'))   # 30个字符,居中对齐,两边补*
************hello*************
>>> print("{0:*<30}".format('hello'))   # 30个字符,左对齐,右边补*
hello*************************
>>> print("{0:3}".format('hello'))      # 长度小于实际字符数,按实际输出
hello
>>> 

<.精度>Indicates two meanings.
For floating-point numbers, precision represents the effective number of digits in the output part of the decimal part.
For strings, it represents the maximum length of the output

>>> print("{0:.2f}".format(12345.67890))      # 保留2位小数
12345.68
>>> print("{0:*^20.2f}".format(12345.67890))  # 20个字符长度,居中对齐,两边补*,保留两位小数
******12345.68******
>>> print("{0:.4}".format("hello"))           # 输出4个字符
hell

浮点数类型
eLowercase letters eexponential form of
Ecapital letters Eexponential form
fstandard form of
%a percentage of float

>>> print("{0:e},{0:E},{0:f},{0:%}".format(123.456))
1.234560e+02,1.234560E+02,123.456000,12345.600000%
>>> print("{0:.2e},{0:.2E},{0:.2f},{0:.2%}".format(123.456))
1.23e+02,1.23E+02,123.46,12345.60%

Print needs to pay attention to

printIt will always end with an invisible "new line" character ( \n), so repeated calls to print will print on separate lines. To prevent this newline character from appearing during printing, you can endspecify that it should end with a blank:

print('a', end='')
print('b', end='')

Output

ab

Escape character

The backslash character \is a special character that represents escape in a string, that is, the character and the next adjacent character form a new meaning.
\nRepresents a newline, \\represents a backslash, \’represents a single quotation mark,
\”represents a double quotation mark, \trepresents a tab characterTab

Insert picture description here

>>> print("hello\nworld\t世界你好")
hello
world	世界你好

Guess you like

Origin blog.csdn.net/weixin_39333120/article/details/109380409