Python string formatted output mode

There are two ways to format a string: percent sign and format.

Among them, the percent sign method is relatively old, while the format method is more advanced, in an attempt to replace the old method. At present, the two coexist.

1. Percent sign method

format:%[(name)][flags][width].[precision]typecode

(name)    可选,用于选择指定的key
flags        可选,可供选择的值有:
    + 右对齐:正数的加正号,负数的加负号
    - 左对齐:正数前没有负号,负数前加负号
width    可选,占有宽度
.precision    可选,小数点后保留的位数
typecode     必选
    s,获取传入的对象__str__方法的返回值,并将其格式化到指定位置
    r,获取传入对象的__repr__方法的返回值,并将其格式化到指定位置
    c,整数:将数字转换成其unicode对应的值,10进制范围为0 <= i <=1114111
    o,将整数转换成八进制表示,并将其格式化到指定位置
    x,将整数转换成16进制,并将其格式化到指定位置
    d,将整数,浮点数转化为十进制表示,并将其格式化到指定位置

example:

>>> s = 'hello, %s!' % 'python'
>>> s
'hello, python!'

>>> s = 'hello, %s, %d!' % ('python', 2018)
>>> s
'hello, python, 2018!'

>>> s = 'hello, %(name)s, %(year)d!' % {
    
    'name': 'python', 'year': 2018}
>>> s
'hello, python, 2018!'

>>> s = 'hello, %(name)+10s, %(year)-10d!' % {
    
    'name': 'python', 'year': 2018}
>>> s
'hello,     python, 2018      !'

>>> s = 'hello, %(name)s, %(year).3f!' % {
    
    'name': 'python', 'year': 2018}
>>> s
'hello, python, 2018.000!'

The difference between %r and %s:

%r is better for debugging, because it displays the raw data of the variable, while other symbols are used to display the output to the user.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
>>> a = 'sunday'
>>> print("Today is %s" % a)
Today is sunday
>>> print("Today is %r" % a)
Today is 'sunday'  # 格式化部分用单引号输出

>>> from datetime import datetime
>>> d = datetime.now()
>>> print('%s' % d)
2018-09-10 08:52:00.769949
>>> print('%r' % d)
datetime.datetime(2018, 9, 10, 8, 52, 0, 769949)  # 可以看见与上面输出存在明显的区别

2.format method

>>> s = 'hello, {}, {}'.format('python', 2018)
>>> s
'hello, python, 2018'

>>> s = 'hello, {0}, {1}, hi, {0}'.format('python', 2018)
>>> s
'hello, python, 2018, hi, python'

>>> s = 'hello, {name}, {year}, hi, {name}'.format(name='python', year=2018)
>>> s
'hello, python, 2018, hi, python'

>>> s = 'hello, {:s}, {:d}, hi, {:f}'.format('python', 2018, 9.7)
>>> s
'hello, python, 2018, hi, 9.700000'

Guess you like

Origin blog.csdn.net/qdPython/article/details/112787005