python格式化字符串

第一种:

print('%2d-%02d' % (3, 1))

print('%.2f' % 3.1415926)

# convert an int value to a string and to represent it as a hexadecimal number
print('%x' % 23004)

# refer to variable substitutions by name
print('Hey %(name)s, there is a 0x%(errno)x error!' % {"name": 'jiangwenwen', "errno": 12345 })

第二种:

print('Hello, {}'.format('jiangwenwen'))

print('Hey {name}, there is a 0x{errno:x} error!'.format(name='jiangwenwen', errno=1))

print('Hello, {0}, 成绩提升了 {1:.1f}%'.format('小明', 17.125))

第三种:

name = 'jiangwenwen'
age = 24

print(f'My name is {name}, I am {age} years old!')

第四种:

from string import Template
template = Template('Hello, $name')
print(template.substitute(name=name))

原文地址:https://www.cnblogs.com/jiangwenwen1/p/11565970.html