String Format 举例¶
2024-11-08
难度: 1
时长: 30 min
一些python str.format() 的例子,由 Kimi 创作。
Python 的 str.format() 方法是一种字符串格式化操作,它允许你插入变量或值到字符串中的特定位置。以下是一些使用 str.format() 方法的例子:
基本使用¶
# 使用位置参数
"Hello, {0}!".format("world")
# 使用关键字参数
"Hello, {name}!".format(name="world")
# 结合位置和关键字参数
"{0} is {1}".format("The sky", "blue")
数字格式化¶
# 整数格式化
"{:d}".format(42) # 输出 '42'
# 浮点数格式化
"{:.2f}".format(3.14159) # 输出 '3.14'
# 科学计数法
"{:e}".format(1000) # 输出 '1.000000e+3'
# 百分比
"{:.2%}".format(0.25) # 输出 '25.00%'
对齐和填充¶
# 左对齐,默认填充空格
"{:<10}".format("left")
# 右对齐,默认填充空格
"{:>10}".format("right")
# 居中对齐,默认填充空格
"{:^10}".format("center")
# 使用特定字符填充
"{:*^10}".format("center")
宽度和精度¶
# 设置字段宽度
"{:10}".format("foo") # 输出 'foo '
# 设置精度
"{:.3f}".format(3.14159) # 输出 '3.142'
类型特定格式化¶
# 十六进制
"{:x}".format(255) # 输出 'ff'
# 二进制
"{:b}".format(255) # 输出 '11111111'
# 八进制
"{:o}".format(255) # 输出 '377'
复杂对象格式化¶
# 格式化字典
"{0[姓]} {0[名]}".format({"姓": "王", "名": "小明"}) # 输出 '王小明'
# 格式化列表
"{0[0]} {0[1]}".format(["apple", "banana"]) # 输出 'apple banana'
# 格式化对象属性
class Person:
def __init__(self, name):
self.name = name
"{0.name}".format(Person("Alice")) # 输出 'Alice'
使用索引和切片¶
# 索引
"{0[3]}".format("Hello World") # 输出 'o'
# 切片
"{0[1:5]}".format("Hello World") # 输出 'ello'
这些例子展示了 str.format() 方法的多样性和灵活性,可以根据需要进行调整和扩展。