【发布时间】:2018-05-19 10:33:01
【问题描述】:
我有一串字节,我想在 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]:
如何指定多个字符串字面量?
【问题讨论】:
-
是否更准确地说您试图让一个变量同时保存 3 种不同类型的数据?
-
@ScottHunter 不。我正在尝试保存 one 原始字节数组(替换值,因此是 f 字符串)。我想完全取消
r,但re模块似乎强烈推荐它。
标签: python string byte rawstring