Skip to main content
 首页 » 编程设计

python之如何一次使用多个字符串文字

2024年09月07日27exmyth

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

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

请您参考如下方法:

字符串插值仅限于字符串,不能用于字节。这是地址 in the PEP :

For the same reason that we don't support bytes.format(), you may not combine 'f' with 'b' string literals. The primary problem is that an object's __format__() method may return Unicode data that is not compatible with a bytes string.


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

>>> rf'Hello {user_name}, nice to see you! :)'.encode() 
b'Hello Simon, nice to see you! :)'