Python提供了很多种格式化方式(包括但不限于以下几种):
name = 'jack'
age = -0.5
print(name, 'is', age, 'years old.')
jack is -0.5 years old.
name = 'jack'
age = -0.5
print(name + ' is ' + str(age) + ' years old.')
jack is -0.5 years old.
name = 'jack'
age = -0.5
print('%s is %.2f years old.'%(name, age))
jack is -0.50 years old.
name = 'jack'
age = -0.5
print(f'name is {name}')
print(f'{name}\'s age is {age}')
print(f'{name.upper()}')
print(f'{name[0]}')
name is jack
jack's age is -0.5
JACK
j
name = 'jack'
age = -0.5
print('name={}, age={}'.format(name, age))
print('name={1}, age={0}'.format(age, name))
print('name={a}, age={b}'.format(a=name, b=age))
name=jack, age=-0.5
name=jack, age=-0.5
name=jack, age=-0.5
name = 'jack'
age = -0.5
print(format(name))
print(format(age, '5f'))
jack
-0.500000
from string import Formatter
form = Formatter()
name = 'jack'
age = -0.5
print(form.format('name={}, age={}', name, age))
print(form.format('name={1}, age={0}', age, name))
print(form.format('name={a}, age={b}', b=age, a=name))
name=jack, age=-0.5
name=jack, age=-0.5
name=jack, age=-0.5
name = 'jack'
age = -0.5
print('%(x)s'%{'x':name})
print('%(x).5f'%{'x':age})
jack
-0.50000
from string import Template
name = 'jack'
age = -0.5
s = Template('$a is $b years old').substitute(a=name, b=age)
print(s)
jack is -0.5 years old
原文:https://www.cnblogs.com/malinqing/p/11285603.html