温馨提示×

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

小樊
88
2024-08-10 01:36:37
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

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

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:python print format函数的编码与解码技巧有哪些

0