温馨提示×

Python中字符串格式化的方法是什么

小亿
86
2024-04-02 18:01:56
栏目: 编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

Python中字符串格式化的方法有两种:

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

推荐使用第二种方法,因为它更为灵活,支持更多的格式化选项。

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

推荐阅读:Python中字符串格式化的操作是什么

0