- 不设置指定位置,按默认顺序
- 设置指定位置
- 字典设置参数
- 列表索引设置参数
- 传入对象
- str.format() 格式化数字
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
class AssignValue(object):
def __init__(self, value):
self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value)) # "0" 是可选的
>>> print("{:.2f}".format(3.1415926))
3.14
本文介绍了Python中字符串格式化的几种方式,包括不设置指定位置的默认顺序格式化,通过索引设置位置的格式化,使用字典和列表索引设置参数,以及使用`str.format()`方法格式化数字。示例代码展示了各种用法,帮助理解字符串格式化的灵活性。
2210

被折叠的 条评论
为什么被折叠?



