专业编程基础技术教程

网站首页 > 基础教程 正文

Python 字符串格式化最佳实践:f str, format % Template

ccvgpt 2024-10-12 14:28:54 基础教程 8 ℃

Python 字符串格式化最佳实践

  • 字符串格式(%运算符)
  • (str.format)
  • 字符串插值 f 字符串 (Python 3.6+)
  • 模板字符串(标准库)


Python 字符串格式化提示和最佳实践

Python 字符串格式化最佳实践:f str, format % Template

>>>

>>> errno = 50159747054
>>> name = 'Bob'

根据这些变量,生成包含简单错误消息的输出字符串:

>>>

'Hey Bob, there is a 0xbadc0ffee error!'


1字符串格式(%运算符)

Python 中的字符串具有独特的内置操作,可以使用运算符访问该操作。

>>>

>>> 'Hello, %s' % name
"Hello, Bob"


可以使用格式说明符将值转换为字符串并将其表示为十六进制数:%xint

>>>

>>> '%x' % errno
'badc0ffee'

单个字符串中进行多个替换,则包装在元组中,如下所示:%

>>>

>>> 'Hey %s, there is a 0x%x error!' % (name, errno)
'Hey Bob, there is a 0xbadc0ffee error!'

如果将映射传递给运算符,也可以在格式字符串中按名称引用变量替换:%

>>>

>>> 'Hey %(name)s, there is a 0x%(errno)x error!' % {
...     "name": name, "errno": errno }
'Hey Bob, there is a 0xbadc0ffee error!'

这使格式字符串更易于维护,并且将来更易于修改。


(str.format)

Python 3引入了一种进行字符串格式化的新方法 .format() 来处理格式化。%

>>>

>>> 'Hello, {}'.format(name)
'Hello, Bob'

可以按名称引用变量替换,并按所需的任何顺序使用它们。这是一个非常强大的功能,因为它允许重新排列显示顺序,而无需更改传递给的参数:format()

>>>

>>> 'Hey {name}, there is a 0x{errno:x} error!'.format(
...     name=name, errno=errno)
'Hey Bob, there is a 0xbadc0ffee error!'


f 字符串 (Python 3.6+)

Python 3.6 添加了一种新的字符串格式化方法,称为格式化字符串文字或“f 字符串”。这种格式化字符串的新方法允许您在字符串常量中使用嵌入式 Python 表达式。下面是一个简单的示例

>>>

>>> f'Hello, {name}!'
'Hello, Bob!'

如您所见,这会在字符串常量前面加上字母 “”,因此得名“f-strings”。这种新的格式语法功能强大。因为您可以嵌入任意 Python 表达式,所以您甚至可以使用它进行内联算术。

>>>

>>> a = 5
>>> b = 10
>>> f'Five plus ten is {a + b} and not {2 * (a + b)}.'
'Five plus ten is 15 and not 30.'

格式化字符串文本是一种 Python 解析器功能,可将 f 字符串转换为一系列字符串常量和表达式。然后,它们连接起来构建最终的字符串。

假设您有以下包含 f 字符串的函数:greet()

>>>

>>> def greet(name, question):
...     return f"Hello, {name}! How's it {question}?"
...
>>> greet('Bob', 'going')
"Hello, Bob! How's it going?"

>>>

>>> def greet(name, question):
...    return "Hello, " + name + "! How's it " + question + "?"


>>>

>>> import dis
>>> dis.dis(greet)
  2           0 LOAD_CONST               1 ('Hello, ')
              2 LOAD_FAST                0 (name)
              4 FORMAT_VALUE             0
              6 LOAD_CONST               2 ("! How's it ")
              8 LOAD_FAST                1 (question)
             10 FORMAT_VALUE             0
             12 LOAD_CONST               3 ('?')
             14 BUILD_STRING             5
             16 RETURN_VALUE

字符串文本还支持该方法的现有格式字符串语法。这使您可以解决我们在前两节中讨论的相同格式问题:str.format()

>>>

>>> f"Hey {name}, there's a {errno:#x} error!"
"Hey Bob, there's a 0xbadc0ffee error!"

Python 的新格式化字符串文字类似于 ES2015 中添加的 JavaScript 模板文字。


#4 模板字符串(标准库)

这是Python中字符串格式化的另一个工具:模板字符串。这是一种更简单且功能较弱的机制


>>>

>>> from string import Template
>>> t = Template('Hey, $name!')
>>> t.substitute(name=name)
'Hey, Bob!'

Python 的内置模块导入类。模板字符串不是核心语言功能,但它们由标准库中的字符串模块提供。Templatestring

另一个区别是模板字符串不允许格式说明符。

>>>

>>> 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!'


>>>

>>> # This is our super secret key:
>>> SECRET = 'this-is-a-secret'

>>> class Error:
...      def __init__(self):
...          pass

>>> # A malicious user can craft a format string that
>>> # can read data from the global namespace:
>>> user_input = '{error.__init__.__globals__[SECRET]}'

>>> # This allows them to exfiltrate sensitive information,
>>> # like the secret key:
>>> err = Error()
>>> user_input.format(error=err)
'this-is-a-secret'

攻击者如何通过从恶意格式字符串访问字典来提取我们的秘密字符串?模板字符串关闭此攻击媒介。如果正在处理从用户输入生成的格式字符串,这使它们成为更安全的选择:__globals__

>>>

>>> user_input = '${error.__init__.__globals__[SECRET]}'
>>> Template(user_input).substitute(error=err)
ValueError:
"Invalid placeholder in string: line 1, col 1"

应使用哪种字符串格式设置方法?

在如何在 Python 中格式化字符串有这么多选择可能会让人感到非常困惑。

可以参考下图的规则来选择适合自己的访求去格式化字符串。

#妙笔生花创作挑战#

最近发表
标签列表