将常规Python字符串转换为原始字符串

时间:2010-12-11 04:49:08

标签: python string

我有一个字符串s,其内容是可变的。我想把它变成原始字符串。我该怎么做?

r''方法类似的东西。

11 个答案:

答案 0 :(得分:42)

原始字符串不是另一种字符串。它们是在源代码中描述字符串的不同方式。一旦创建了字符串,它就是它。

答案 1 :(得分:30)

我相信你要找的是str.encode(“string-escape”)函数。例如,如果您有一个想要'raw string'的变量:

a = '\x89'
a.encode('unicode_escape')
'\\x89'

注意:对{python 2.x及更早版本

使用string-escape

我正在寻找类似的解决方案并通过以下方式找到解决方案: casting raw strings python

答案 2 :(得分:19)

原始字符串仅适用于字符串文字。它们存在,以便您可以更方便地表达将通过转义序列处理修改的字符串。在字符串文字中写出正则表达式或其他形式的代码时,这尤其有用。如果你想要一个没有转义处理的unicode字符串,只需用ur作为前缀ur'somestring'

答案 3 :(得分:6)

从Python 3.6开始,您可以使用以下内容(类似于@slashCoder):

def to_raw(string):
    return fr"{string}"

my_dir ="C:\data\projects"
to_raw(my_dir)

产生'C:\\data\\projects'。我在Windows 10计算机上使用它来将目录传递给函数。

答案 4 :(得分:2)

由于Python中的字符串是不可变的,因此您不能对其进行“更改”。但是,您可以从s 创建新的原始字符串,如下所示:

raw_s = r'{}'.format(s)

答案 5 :(得分:2)

只是这样的格式:

s = "your string"; raw_s = r'{0}'.format(s)

答案 6 :(得分:1)

s = "hel\nlo"
raws = '%r'%s #coversion to raw string
#print(raws) will print 'hel\nlo' with single quotes.
print(raws[1:-1]) # will print hel\nlo without single quotes.
#raws[1:-1] string slicing is performed

答案 7 :(得分:1)

稍微更正@Jolly1234 的回答: 这是代码:

raw_string=path.encode('unicode_escape').decode()

答案 8 :(得分:0)

对于Python 3,这样做的方法是不添加双反斜杠,而仅保留\n\t等,

a = 'hello\nbobby\nsally\n'
a.encode('unicode-escape').decode().replace('\\\\', '\\')
print(a)

哪个值可以写为CSV:

hello\nbobby\nsally\n

似乎没有其他特殊字符的解决方案,但是在它们前面可能会有一个\。真是可惜解决起来很复杂。

例如,要将包含特殊字符的字符串列表的pandas.Series序列化为文本文件,格式为BERT,期望将每个句子之间的CR和每个文档之间的空行: / p>

with open('sentences.csv', 'w') as f:

    current_idx = 0
    for idx, doc in sentences.items():
        # Insert a newline to separate documents
        if idx != current_idx:
            f.write('\n')
        # Write each sentence exactly as it appared to one line each
        for sentence in doc:
            f.write(sentence.encode('unicode-escape').decode().replace('\\\\', '\\') + '\n')

此输出(对于标记为句子的所有语言的Github CodeSearchNet文档字符串):

Makes sure the fast-path emits in order.
@param value the value to emit or queue up\n@param delayError if true, errors are delayed until the source has terminated\n@param disposable the resource to dispose if the drain terminates

Mirrors the one ObservableSource in an Iterable of several ObservableSources that first either emits an item or sends\na termination notification.
Scheduler:\n{@code amb} does not operate by default on a particular {@link Scheduler}.
@param  the common element type\n@param sources\nan Iterable of ObservableSource sources competing to react first.
A subscription to each source will\noccur in the same order as in the Iterable.
@return an Observable that emits the same sequence as whichever of the source ObservableSources first\nemitted an item or sent a termination notification\n@see ReactiveX operators documentation: Amb


...

答案 9 :(得分:-2)

只需使用编码功能即可。

my_var = 'hello'
my_var_bytes = my_var.encode()
print(my_var_bytes)

然后将其转换回常规字符串

my_var_bytes = 'hello'
my_var = my_var_bytes.decode()
print(my_var)

-编辑-

以下内容不会使字符串成为原始字符串,而是将其编码为字节并进行解码。

答案 10 :(得分:-2)

我想repr功能可以为您提供帮助:

s = 't\n'
repr(s)
"'t\\n'"
repr(s)[1:-1]
't\\n'