- 使用占位符进行格式化输出:
name = 'Alice' age = 25 print('My name is %s and I am %d years old.' % (name, age))
- 使用format方法进行格式化输出:
name = 'Bob' age = 30 print('My name is {} and I am {} years old.'.format(name, age))
- 使用f-string进行格式化输出(Python 3.6及以上版本):
name = 'Charlie' age = 35 print(f'My name is {name} and I am {age} years old.')
- 控制输出格式:
value = https://www.yisu.com/ask/3.14159'The value is {:.2f}'.format(value)) # 输出保留两位小数
- 使用位置参数和关键字参数:
name = 'David' age = 40 print('My name is {0} and I am {1} years old. {0} is a {job}.'.format(name, age, job='teacher'))