发布时间:2022-05-07 09:38:19 人气:182 作者:多测师
1. "旧式字符串解析(%操作符)"
'Hello, %s' % name
"Hello, Bob"
'Hey %(name)s, there is a 0x%(errno)x error!' % {
"name": name, "errno": errno }
'Hey Bob, there is a 0xbadc0ffee error!'
2. "新式"字符串格式化(str.format)
'Hello, {}'.format(name)
'Hello, Bob'
'Hey {name}, there is a 0x{errno:x} error!'.format( name=name, errno=errno)
'Hey Bob, there is a 0xbadc0ffee error!'
3. 字符串插值/f-Strings(Python 3.6+)
python 3.6新出的,本人用了这个之后, 果断抛弃其他方法, 真的太强大了!!!
name = Bob
f'Hello, {name}!'
'Hello, Bob!'
def greet(name, question):
... return f"Hello, {name}! How's it {question}?"
...
greet('Bob', 'going')
"Hello, Bob! How's it going?"
4. 字符串模板法(Python标准库)
templ_string = 'Hey $name, there is a $error error!'
Template(templ_string).substitute(
... name=name, error=hex(errno))
'Hey Bob, there is a 0xbadc0ffee error!'
以上内容为大家介绍了python 字符串格式化,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/