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

posted @ 2019-09-22 09:45  姜文文  阅读(188)  评论(0编辑  收藏  举报