【问题标题】:Behavior of f-strings outside of functions [duplicate]函数之外的 f 字符串的行为 [重复]
【发布时间】:2020-04-27 08:38:15
【问题描述】:

我注意到,当 not 包含在 print() 函数中时,从 Python 控制台运行带有转义字符的 f 字符串的行为会有所不同。例如,包装在 print() 函数中,\n 会按预期运行:

>>>a = 1
>>>b = 'frog' 
>>>c = 3

>>>print(f"""The first variable is {a}\nThe second is {b} and the third is {c}""")
The first variable is 1
The second is frog and the third is 3

直接运行,它的作用不同,将\n 打印为文本。

>>>f"""The first variable is {a}\nThe second is {b} and the third is {c}"""
'The first variable is 1\nThe second is frog and the third is 3'

我的问题是:这种行为变化的根本原因是什么?在其他情况下(例如在查询、写入文本文件等)中使用这种格式化字符串时可能需要注意什么? ?

【问题讨论】:

  • 我发现@APhillips 引用的帖子并没有回答我的问题,主要是因为我没有尝试将字符放在花括号内,我看到\n 字符在大括号之外大括号在输出中被完美格式化。那时我还没有理解 print() 语句的意义。尽管@John Kugelman 支持 Monica 的引用链接确实回答了这个问题(因此得到了赞成),但它并没有出现在搜索中,原因是转义字符 \n 没有在控制台中呈现为回车符。跨度>

标签: python python-3.x string formatting


【解决方案1】:

字符串在两种情况下都包含完全相同的数据,这发生在任何字符串上,而不仅仅是 f 字符串。不同的是用来生成字符串显示的函数。

print 使用方法str.__str__() 来显示字符串,而交互式解释器使用str.__repr__()。后一个功能是转义不可打印字符的调试显示。

这里有一些演示。该类表明您可以覆盖默认行为。

>>> s = 'abc\tdef\nghi\bjkl'
>>> print(s)  # are those spaces or a tab?  Where's the i?
abc     def
ghjkl
>>> s   # makes it clear that a tab, newline and backspace are present.
'abc\tdef\nghi\x08jkl'

>>> class Test:
...  def __str__(self):
...    return '__str__'
...  def __repr__(self):
...    return '__repr__'
...
>>> t = Test()
>>> print(t)
__str__
>>> t
__repr__

【讨论】:

    【解决方案2】:

    这不是 f-strings 独有的。 python 中的每个字符串都会发生这种情况。

    >>> 'a\nb'
    'a\nb'
    >>> print('a\nb')
    a
    b 
    

    print 将您的字符串发送到流中,并在那里进行解释。当你自己输入字符串时,它会返回它的实际值,无需额外解释*。

    *编辑:正如所指出的,它通过__repr__

    【讨论】:

    • 没有print的加法解释。 __repr__ 被调用并且不可打印的字符被转义。字符串本身不包含\n(换行代码点的两个字符转义码)。
    • 我明白了。你能告诉我为什么当我使用'a\nb'.__repr__() 时我得到"'a\\nb'",但当我单独使用它时只有'a\nb'?是在__repr__ 上调用__repr__ 吗?
    • 是的,完全正确。它显示了repr() 返回的字符串的repr()。您可以看到它以单引号开头和结尾,并且有一个文字反斜杠和n 字符而不是换行符。
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 2021-12-05
    • 2015-12-30
    • 1970-01-01
    • 2017-03-21
    • 2020-02-06
    • 2020-12-06
    • 2023-03-05
    相关资源
    最近更新 更多