Convert regular Python string to raw string
我有一个字符串
类似于
我相信您正在寻找的是str.encode(" string-escape")函数。例如,如果您有一个要"原始字符串"的变量:
1 2 3 | a = '\\x89' a.encode('unicode_escape') '\\\\x89' |
注意:对于Python 2.x和更早版本,请使用
我在寻找类似的解决方案,并通过以下方式找到了解决方案:
转换原始字符串python
原始字符串不是另一种字符串。它们是在源代码中描述字符串的另一种方式。一旦创建了字符串,它就是它的意思。
原始字符串仅适用于字符串文字。它们的存在是为了使您可以更方便地表达将由转义序列处理修改的字符串。在用字符串文字写出正则表达式或其他形式的代码时,这尤其有用。如果您想要一个不进行转义处理的unicode字符串,只需在其前面加上
由于Python中的字符串是不可变的,因此您无法"使之"有所不同。但是,您可以从
从Python 3.6开始,您可以使用以下内容(类似于@slashCoder):
1 2 3 4 5 | def to_raw(string): return fr"{string}" my_dir ="C:\\data\\projects" to_raw(my_dir) |
产生
对于Python 3,这样做的方法是不添加双反斜杠,而只保留
1 2 3 4 5 6 | a = 'hello\ bobby\ sally\ ' a.encode('unicode-escape').decode().replace('\\\\\\\', '\\\') print(a) |
给出一个可以写为CSV的值:
1 2 3 | hello\ bobby\ sally\ |
似乎没有其他特殊字符的解决方案,但是可能在它们之前加了一个\。真是可惜解决那将是复杂的。
例如,要将包含特殊字符的字符串列表的
1 2 3 4 5 6 7 8 9 10 11 12 | 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('\ ') # Write each sentence exactly as it appared to one line each for sentence in doc: f.write(sentence.encode('unicode-escape').decode().replace('\\\\\\\', '\\\') + '\ ') |
输出(对于标记为句子的所有语言的Github CodeSearchNet文档字符串):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | Makes sure the fast-path emits in order. @param value the value to emit or queue up\ @param delayError if true, errors are delayed until the source has terminated\ @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\ a termination notification. Scheduler:\ {@code amb} does not operate by default on a particular {@link Scheduler}. @param the common element type\ @param sources\ an Iterable of ObservableSource sources competing to react first. A subscription to each source will\ occur in the same order as in the Iterable. @return an Observable that emits the same sequence as whichever of the source ObservableSources first\ emitted an item or sent a termination notification\ @see ReactiveX operators documentation: Amb ... |
只是这样的格式:
1 2 3 4 5 6 7 8 | s ="hel\ lo" raws = '%r'%s #coversion to raw string #print(raws) will print 'hel\ lo' with single quotes. print(raws[1:-1]) # will print hel\ lo without single quotes. #raws[1:-1] string slicing is performed |
我想repr函数可以帮助您:
1 2 3 4 5 6 7 8 | s = 't\ ' repr(s) "'t\\\ '" repr(s)[1:-1] 't\\\ ' |
只需使用编码功能即可。
1 2 3 | my_var = 'hello' my_var_bytes = my_var.encode() print(my_var_bytes) |
然后将其转换回常规字符串
1 2 3 | my_var_bytes = 'hello' my_var = my_var_bytes.decode() print(my_var) |
- 编辑 -
以下代码不会使字符串成为原始字符串,而是将其编码为字节并进行解码。