【问题标题】:How to generate the string 'x000' in Python?如何在 Python 中生成字符串“x000”?
【发布时间】:2021-09-18 03:22:42
【问题描述】:

我想在 python 中运行以下命令。我需要打印'\0000'。我尝试不同的方式来打印它。我得到了“\x00”或“\000”。如何在 python 中生成字符串'\000'?非常感谢。

gsutil cp xxxxx.csv - | tr -d '\000' | gsutil cp - xxxxx.csv
>>> remove_string='''\000'''

>>> remove_string

'\x00'


>>> remove_string='\\000'
>>> remove_string
'\\000'
>>> remove_string=r'\\000'

>>> remove_string
'\\\\000'
>>> remove_string=r'\000'
>>> remove_string
'\\000'

【问题讨论】:

  • 反斜杠(\)在字符串中有特殊含义,所以需要转义——'\\000'r'\000'
  • 我试过了,但还是不能得到\000
  • 当您在 Python 交互模式下键入表达式时,您会看到值的 repr(),而不是其 str()'\\000' 你想要的字符串的repr()
  • 你想在这里做什么? \000 通常意味着一个空字节——你的代码看起来只是想从输入中删除空字节。在这种情况下,\x00\0\000 都将是等效的。也许尝试为您打算如何使用此字符串提供更多上下文。
  • remove_string='\\000' 之后尝试print(remove_string)。然后你得到包含的字符串,它是你想要的 4 个字符。 shell 打印repr(remove_string),它添加了引号和转义符,使字符串看起来像 python 文字。

标签: python python-3.x string


【解决方案1】:

字符串字面量是您在 Python 编译成 str 对象的程序中键入的文本。 Python 特别对待反斜杠字符\ - 它允许您输入不在键盘上的字符。但有时您需要反斜杠,以便使用\\ 对其进行转义。显示字符串时,python 有reprstr 版本的字符串。 repr 为您提供文字刺痛版本,而str 为您提供真实字符串。 “literal”实际上是 not 字符串,这有点令人困惑。如果你转义字符串并打印它,你会看到真正的字符。

>>> remove_string = '\\000'
>>> remove_string
'\\000'
>>> print(remove_string)
\000

您还使用了原始字符串。前面加上“r”告诉python停止使用反斜杠作为字符串文字中的特殊字符串。但是,如果您稍后获取该字符串的 repr,您仍然会获得特殊的字符串文字表示。不,有问题,因为字符串是正确的。

>>> remove_string = r'\000'
>>> remove_string
'\\000'
>>> print(remove_string)
\000

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 2015-10-29
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    相关资源
    最近更新 更多