1、字符串格式化(format)
format()
方法允许格式化字符串的选定部分。
有时文本的某些部分是无法控制的,也许它们来自数据库或用户输入。
要控制这些值,请在文本中添加占位符(花括号{}
),然后通过format()
方法运行这些值:
例如:
添加一个占位符,输出字符串:
y = 49 txt = "My age is {} years old" print(txt.format(y))
可以在大括号内添加参数以指定如何转换值:
例如:
显示为一个数字与两个小数:
txt = "我的体重是{:.2f} KG"
在我们的String format()参考中查看所有格式类型。
2、格式化多个值
如果要使用更多值,只需将更多值添加到format()方法:
print(txt.format(txt, age, count))
并添加更多占位符:
例如:
txt = 3 age = 13 count = 41 myorder = "txt = {} age = {} count = {:.2f} " print(myorder.format(txt, age, count))
3、索引号
可以使用索引号(一个在花括号{0}
中的数字)来确保这些值被放在正确的占位符中:
例如:
txt = 3 age = 13 count = 41 myorder = "txt = {0} age = {1} count = {2:.2f} " print(myorder.format(txt, age, count))
另外,如果要多次引用相同的值,请使用索引号:
例如:
name = "cjavapy"
url = "https://www.cjavapy.com" txt = "name1 = {1} name2 = {1} url = {0}" print(txt.format(age, name))
4、命名索引
还可以通过在大括号{name}
中输入名称来使用命名索引,但是在传递参数值txt.format(name = "python")
时必须使用名称:
例如:
myorder = "this is {name}, it is a {type}." print(myorder.format(name = "cjavapy", type = "website"))