2

我有一串字节,我试图在 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]:

如何指定多个字符串文字?

4

1 回答 1

2

字符串插值仅限于字符串,不能用于bytes。这在 PEP 中得到解决:

出于我们不支持的相同原因bytes.format(),您不能将 'f' 与 'b' 字符串文字结合使用。主要问题是对象的__format__()方法可能返回与字节字符串不兼容的 Unicode 数据。


解决方法是将字符串手动编码为字节:

>>> rf'Hello {user_name}, nice to see you! :)'.encode()
b'Hello Simon, nice to see you! :)'
于 2018-05-19T10:55:33.917 回答