温馨提示×

python print format函数的格式化输出技巧有哪些

小樊
87
2024-08-10 01:36:37
栏目: 编程语言

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

0