在Python中,格式化字符串可以通过以下几种方法实现:
1. 使用`%`操作符:
name = "张三"
age = 25
print("我的名字是%s,我%d岁了。" % (name, age))
2. 使用`str.format()`方法:
name = "张三"
age = 25
print("我的名字是{},我{}岁了。" .format(name, age))
3. 使用f-string(Python 3.6及更高版本):
name = "张三"
age = 25
print(f"我的名字是 {name},我 {age} 岁了。" )
4. 使用`format`函数:
name = "张三"
age = 25
print("我的名字是{},我{}岁了。" .format(name, age))
以上方法都可以实现字符串的格式化输出。如果需要更复杂的格式设置,可以在大括号`{}`内添加相应的格式说明符。例如:
保留小数点后两位:`{:.2f}`
设置字符串宽度:`{:10}`
设置字符串对齐方式:`{:10}`(右对齐)、`{:^10}`(居中对齐)
示例:
pi = 3.
print(f"圆周率保留两位小数: {pi:.2f} " )
text = "Hello"
print(f"左对齐: {text:10} " )
print(f"居中对齐: {text:^10} " )
这些方法可以帮助你根据需要调整字符串的格式。