Modo de salida con formato de cadena de Python

Hay dos formas de formatear una cadena: signo de porcentaje y formato.

Entre ellos, el método del signo de porcentaje es relativamente antiguo, mientras que el método de formato es más avanzado, en un intento de reemplazar el método antiguo, actualmente coexisten los dos.

1. Método del signo de porcentaje

formato:%[(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,将整数,浮点数转化为十进制表示,并将其格式化到指定位置

ejemplo:

>>> 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!'

La diferencia entre% r y% s:

% r es mejor para la depuración, porque mostrará los datos sin procesar de la variable, mientras que otros símbolos se utilizan para mostrar la salida al usuario.

'''
遇到问题没人解答?小编创建了一个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)  # 可以看见与上面输出存在明显的区别

Método 2.format

>>> 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'

Supongo que te gusta

Origin blog.csdn.net/qdPython/article/details/112787005
Recomendado
Clasificación