我有一个字符串,我试图在re:
中使用user_name = 'Simon'
string = 'Hello {user_name}, nice to see you! :)'
然而,除了使用字节之外,re字符串应该是原始字符串(r
)。
那么如何一次指定字节,f字符串和原始字符串?
我试过了:
user_name = rb'Simon'
string = brf'Hello {user_name}, nice to see you! :)'
可是:
In [1]: user_name = rb'Simon'
...: string = brf'Hello {user_name}, nice to see you! :)'
File "<ipython-input-8-93fb315cc66f>", line 2
string = brf'Hello {user_name}, nice to see you! :)'
^
SyntaxError: invalid syntax
In [2]:
我也试过format()
,但失败了:
In [2]: string = br'Hello {}, nice to see you! :)'.format(user_name)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-9-36faa39ba31d> in <module>()
----> 1 string = br'Hello {}, nice to see you! :)'.format(user_name)
AttributeError: 'bytes' object has no attribute 'format'
In [3]:
如何指定多个字符串文字?
答案 0 :(得分:2)
字符串插值仅限于字符串,不能用于字节。这是in the PEP:
出于同样的原因,我们不支持
bytes.format()
,您可能不会 结合&#39; f&#39;用&#39; b&#39;字符串文字。主要问题是 object的__format__()
方法可能会返回非数据的Unicode数据 兼容字节字符串。
解决方法是将字符串手动编码为字节:
>>> rf'Hello {user_name}, nice to see you! :)'.encode()
b'Hello Simon, nice to see you! :)'