Python Raw Strings

rec*_*gle 22 python string

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

类似于r''方法的东西.

Kar*_*tel 45

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

  • 为了罕见,准确地使用"它是什么",+1 (10认同)
  • 这实际上是错的.这里有另一个答案正确的回答:"原始字符串不会逃避它们内部的任何东西". (7认同)
  • @igorsantos07 不,你很困惑。当你*创建*一个字符串时,你可能需要转义一些东西;但是一旦字符串包含它所包含的内容,“转义它”就不是一个明确定义的操作(当然,您可以通过例如将文字反斜杠解释为转义码来创建具有*不同*内容的字符串)。 (2认同)

Jol*_*234 35

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

a = '\x89'
a.encode('unicode_escape')
'\\x89'
Run Code Online (Sandbox Code Playgroud)

注意:string-escape用于python 2.x及更早版本

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

  • 如果它也对其他人有帮助,我还需要在末尾添加额外的“.decode()”,就像[引用的源](/sf/answers/169969271/)一样,以获得像我一样的东西仅从“r”string_goes_here”获取。然而,这是一个相当复杂的情况,我正在复制像[此处](/sf/ask/4244847771/)这样的问题并解决。 (5认同)
  • 在python 3.5.1上:`LookupError:未知编码:string-escape` (4认同)
  • 对我来说,“r'' 运算符”和 .encode() 似乎不一样。这三个: '\bla\ \n' --- r'\bla\ \n' --- ('\bla\ \n').encode("unicode_escape").decode() 似乎都给出了不同的字符串: '\x08la\\ \n' --- '\\bla\\ \\n' --- '\\x08la\\\\ \\n' (3认同)
  • 这就是解决方案。 (2认同)

sla*_*der 32

由于 Python 中的字符串是不可变的,因此您不能“使它”有任何不同。但是,您可以从 中创建一个新的原始字符串s,如下所示:

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

  • `>>> raw_s = r'{}'.format(normal) >>> raw_s 'The\n' >>> 正常 'The\n' >>> raw=r"The\n" >>> raw ' \\n'` 不提供与原始输出相同的输出 (2认同)
  • 这没有任何作用。`r'{}'.format('\n') == '\n'`。`r` 前缀仅适用于字符串文字内部的内容,即大括号。 (2认同)

Sin*_*ion 19

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

  • 唉,TokenMacGuy就是这个名字.我的主机运行窗口.*real*原因我不使用原始字符串进行文件路径是因为我从不硬编码路径名. (8认同)
  • 我不希望@TokenMacGuy知道这一点,但它们对于在Windows上定义路径也很有用,它使用反斜杠作为路径中的分隔符,例如`r'C:\ Python27\Tools\Scripts\2to3.py "` (6认同)

dhe*_*inz 13

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

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

my_dir ="C:\data\projects"
to_raw(my_dir)
Run Code Online (Sandbox Code Playgroud)

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

  • `>>> def to_raw(string): ... return fr"{string}" ... >>> 正常 'The\n' >>> to_raw(normal) 'The\n' >>> raw 'The \\n'` 不提供与原始输出相同的输出 (3认同)
  • 这实际上没有任何作用。`my_dir` 已经是 `'C:\\data\\projects'` 因为 `\d` 和 `\p` 是无法识别的转义序列,所以反斜杠被保留。[无法识别的转义序列将在 Python 的未来版本中引发 `SyntaxError`](https://docs.python.org/3/reference/lexical_analysis.html#index-23)。还可以尝试“my_dir = 'C:\Users'”,它会立即引发“SyntaxError”。 (3认同)
  • @ChemEnger `返回字符串` 也同样有效;在所有“string”是实际字符串而不是“int”的情况下,“fr"{string}" == string”。 (2认同)

rju*_*ney 5

对于Python 3,顺便可以做到这一点不添加双反斜线和简单的蜜饯\n\t等是:

a = 'hello\nbobby\nsally\n'
a.encode('unicode-escape').decode().replace('\\\\', '\\')
print(a)
Run Code Online (Sandbox Code Playgroud)

这给出了一个可以写为 CSV 的值:

hello\nbobby\nsally\n
Run Code Online (Sandbox Code Playgroud)

其他特殊字符似乎没有解决方案,但是,在它们之前可能会有一个 \ 。这是一个无赖。解决这个问题会很复杂。

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

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')
Run Code Online (Sandbox Code Playgroud)

此输出(对于标记为句子的所有语言的 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


...
Run Code Online (Sandbox Code Playgroud)


小智 5

就这样格式化:

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