在Python学习过程中,遇到字符串格式化输出,故记录一下。
以前字符串格式化方法常采用%
,这种方法在将来的版本中可能被遗弃。
以后尽量采用字符串的format
方法,该方法较%
更加的灵活和强大。format()
方法格式化特定的值,并将它们嵌入待格式化字符串中的占位符处。该占位符为curly brackets
:{}
。
用法
string
.format(
value1, value2,…)
value1, value2, … 输入参数值,required
;
这些值可以是以逗号分隔的列表(list)
、键值列表key=value
、或者是它们的组合等,这些值可以是任意数据类型。
占位符可以通过名字索引{iddex_name}
,数字索引{0}
,或者空的占位符{ }
等。
例子
- 通过位置直接嵌入
test1="My name is {}. I'm {}.".format('SeisTang',18)
test2="My name is {0}. I'm {1}.".format('SeisTang',18)
test3="My name is {0}. I'm {1}. You can call me {0}.".format('SeisTang',18)
print(test1)
print(test2)
print(test3)
output:
My name is SeisTang. I’m 18.
My name is SeisTang. I’m 18.
My name is SeisTang. I’m 18. You can call me SeisTang.
可以看到,format
会把参数values
按照位置顺序嵌入到字符串string
中,同一个参数可以嵌入多次。
- 通过列表
list
来嵌入
list1=['SeisTang',18]
list2=['Hello','Tang']
test1="My name is {0[0]}. I'm {0[1]}. {1[0]} {1[1]}.".format(list1,list2)
test2="My name is {tl1[0]}. I'm {tl1[1]}. {tl2[0]} {tl2[1]}.".format(tl1=list1,tl2=list2)
print(test1)
print(test2)
output
My name is SeisTang. I’m 18. Hello Tang.
My name is SeisTang. I’m 18. Hello Tang.
- 通过
key-value
来嵌入
test1="My name is {name}. I'm {age}.".format(name='SeisTang',age=18)
print(test1)
output
My name is SeisTang. I’m 18.
- 当然也可以通过字典的键进行嵌入
dict={'name':'SeisTang','age':18}
test1="My name is {0[name]}. I'm {0[age]}.".format(dict)
print(test1)
输出与上面相同。
- 也可以使用
**
符号将上面dict
作为传递的关键参数。
格式转换
针对数字,如3.1415926
,希望只输出小数点后两位,可在占位符中加入{:.2f}
这些规则与C语言中类似,此处不再赘述,可查阅其他相关文献资料。
test1="How {} are you? I'm {:.2f}m.".format('tall',1.8321)
print(test1)
output
How tall are you? I’m 1.83m.
如有错误,请指正,非常感谢!