1 字符串拼接:
字符串格式化,可以处理非常复杂的字符串拼接
print "My name is %s and weight is %d kg!" % (
'Zara',
21)
输出为:
My
name is Zara
and weight
is 21 kg!
常用占位符号: %s, %i, %d, %c … …
还可以控制输出的格式,比如对齐方式,精度,等等 可参考:http://www.runoob.com/python/python-strings.html
2 string.format()
字符串格式化函数, 通过函数的形式取代特殊的语法形式,更容易理解和统一风格!
同时可以变量复用,或者嵌套插入!
>>>
"{} {}".
format(
"hello",
"world")
# 不设置指定位置,按默认顺序
>>>
"{0} {1}".
format(
"hello",
"world")
# 设置指定位置
>>>
"{1} {0} {1}".
format(
"hello",
"world")
# 设置指定位置
还可以设置参数: 详情参考:http://www.runoob.com/python/att-string-format.html