【问题标题】:What is the right way to encode a string with backslashes? [duplicate]用反斜杠编码字符串的正确方法是什么? [复制]
【发布时间】:2019-02-08 01:37:56
【问题描述】:

在给定的示例中:“\info\more info\nName” 我怎么把它变成字节

我尝试使用 unicode-escape 但这似乎不起作用:(

data = "\info\more info\nName"
dataV2 = str.encode(data)
FinalData = dataV2.decode('unicode-escape').encode('utf_8')
print(FinalData)

这是我应该得到的 b'\info\more info\nName' 但是发生了一些意想不到的事情,我在终端中收到了 DeprecationWarnings 我假设它是因为反斜杠导致无效序列,但我需要它们用于这个项目

【问题讨论】:

  • 简短的回答是使用原始字符串文字。我确定 Stack Overflow 上已经有一个很好的副本,我只是想找到一个。

标签: python encode


【解决方案1】:

字符前的反斜杠表示试图转义后面的字符以使其成为某种特殊字符。你会得到DeprecationWarning,因为 Python (finally) 会使无法识别的转义错误成为错误,而不是默默地将它们视为文字反斜杠后跟字符。

要解决此问题,请将反斜杠加倍(不确定您是否打算换行;如果是,请将 n 之前的反斜杠加倍):

data = "\\info\\more info\\nName"

或者,如果您希望所有反斜杠都是文字反斜杠(\n 不应该是换行符),那么您可以使用带有 r 前缀的原始字符串:

data = r"\info\more info\nName"

这会禁用除引号字符本身之外的所有内容的反斜杠插值。

请注意,如果您只是让data 在交互式解释器中回显,它会将反斜杠显示为双倍(因为它隐式使用了strrepr,这是您要复制的内容)。为避免这种情况,请print str 看看它的实际外观:

>>> "\\info\\more info\\nName"  # repr produced by simply evaluating it, which shows backslashes doubled, but there's really only one each time
"\\info\\more info\\nName"
>>> print("\\info\\more info\\nName") # print shows the "real" contents
\info\more info\nName
>>> print("\\info\\more info\nName") # With new line left in place
\info\more info
Name
>>> print(r"\info\more info\nName") # Same as first option, but raw string means no doubling backslashes
\info\more info\nName

【讨论】:

    【解决方案2】:

    你可以用另一个反斜杠转义一个反斜杠。

    data = "\\info\\more info\nName"
    

    您也可以对不需要转义的部分使用原始字符串。

    data = r"\info\more info""\nName"
    

    请注意,如果最后一个字符是反斜杠,则原始字符串不起作用。

    【讨论】:

      猜你喜欢
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-27
      • 2023-04-08
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      相关资源
      最近更新 更多