组合 Python f 字符串和 r 字符串未按预期运行

Combining Python f-string and r-string not behaving as expected

我有一个包含字符串的变量,我想按字面打印,所以换行符被转义了。打印变量不转义换行符:

bad_string = 'http://twitter.com/blo\r\n+omberg'
print(bad_string)
>>> http://twitter.com/blo
+omberg

使用 r 字符串打印值会得到我想要的结果:

print(r'http://twitter.com/blo\r\n+omberg')
>>> http://twitter.com/blo\r\n+omberg

但是,将 f 字符串与变量一起使用,并将其与 r 字符串组合,不会:

print(rf'{bad_string}')
>>> http://twitter.com/blo
+omberg

我很困惑为什么会这样。我希望 r 和 f 字符串的组合能够按字面打印它。如何使用 f 字符串打印字符串变量的字面值?

我正在使用 Python 3.6.13

原始字符串只关心静态文字部分,因此您的 rf'{bad_string}'bad_string 相同。

根据它的用途,repr 内置可能是您需要的

In [71]: print(repr("string\nwith\nnewline"))
'string\nwith\nnewline'

或者您可以使用 replace 方法简单地替换换行符。

还有 unicode_escape“编码”,但这也会替换任何非 ascii 值:

In [77]: "\n".encode("unicode_escape").decode()
Out[77]: '\n'

In [78]: "仮".encode("unicode_escape").decode()
Out[78]: '\u4eee'