【问题标题】:How to print a single backslash in python in a string?如何在字符串中打印python中的单个反斜杠?
【发布时间】:2019-06-20 15:53:17
【问题描述】:

在 python 中(3x 版本)

'\' # this is error no doubt
'\\' # this prints two backslashes ,i.e., '\\'
r'\' # this also gives error
'anytext \ anytext' # gives 'anytext \\ anytext'

rR 都试过了,但没有用 试图转义转义字符\,即'\\',但没有工作enter image description here

【问题讨论】:

  • '\\' 应该可以工作
  • 请发布实际代码,而不仅仅是您尝试的字符串。
  • 这不起作用看到它打印0.60\textbackslash pm0.073我想要0.60\pm0.073

标签: python-3.x


【解决方案1】:

在 IDLE(Python 的集成开发和学习环境)中,表达式值的表示回显到标准输出。

正如https://docs.python.org/3/library/idle.html 解释的那样:

repr 函数用于表达式值的交互式回显。 它返回输入字符串的更改版本,其中控制 代码、一些 BMP 代码点和所有非 BMP 代码点被替换 带有转义码。

如果要打印字符串,请使用print() 函数。否则你会得到它的表示

考虑在 IDLE 中输入以下代码:

>>> hitman_str = "Agent \ 47"
>>> print(hitman_str) # We see only one slash when using print
Agent \ 47
>>> hitman_str # This shows the representation, which shows two slashes
'Agent \\ 47'
>>> print(repr(hitman_str)) # Same as above
'Agent \\ 47'

有多种方法可以获取只有一个斜杠的字符串:

single_slash1 = "\\"
>>> print(single_slash1)
\
>>> single_slash2 = "\ "[0]
>>> print(single_slash2)
\
>>> single_slash1 == single_slash2
True

同样,有多种方法可以得到一个带有两个连续斜杠的字符串:

>>> two_slashes1 = "\\\\"
>>> print(two_slashes1)
\\
>>> print(repr(two_slashes1))
'\\\\'
>>> two_slashes1
'\\\\'
>>> len(two_slashes1)
2
>>> two_slashes2 = r"\\"
>>> print(two_slashes2)
\\
>>> print(repr(two_slashes2))
'\\\\'
>>> two_slashes2
'\\\\'
>>> len(two_slashes2)
2

我们可以确认hitman_str只有一个斜线:

>>> hitman_str.count(single_slash1)
1

我们可以遍历字符串并打印每个字符及其 Unicode 代码点。 正如预期的那样,这仅显示一个斜线:

>>> for char in hitman_str:
    print(char, ord(char))


A 65
g 103
e 101
n 110
t 116
  32
\ 92
  32
4 52
7 55

原始字符串非常方便,特别是对于 Windows 路径,如果您不想使用 os.pathpathlib

>>> filename = r"C:\Users\Lee Hong\Documents\New Letters\Impatient 1999-06-14.txt" # Works fine
>>> filename = "C:\Users\Lee Hong\Documents\New Letters\Impatient 1999-06-14.txt" # Error
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
>>> raw_str = r"This \\\has \11 \\slashes \\and \no \line \break"
>>> print(raw_str)
This \\\has \11 \\slashes \\and \no \line \break
>>> raw_str.count(single_slash1)
11

有关更多信息,包括需要注意的转义序列列表,请参阅https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

【讨论】:

  • 这不起作用看到它打印0.60\textbackslash pm0.073我想要0.60\pm0.073
  • 如果你想打印0.60\pm0.073,你可以使用一个原始字符串和一个反斜杠(print(r"0.60\pm0.073")),或者一个简单的字符串和两个反斜杠(print("0.60\\pm0.073"))。
【解决方案2】:

如果我正确理解您的问题,例如:print("\\")?

【讨论】:

  • 问题很模糊,因为它显然打印了一个反斜杠,但它太简单了,所以问号。
  • 但它没有像我预期的那样打印一个反斜杠
  • Python 3.7.3(默认,2019 年 3 月 27 日,09:23:15)[Clang 10.0.1 (clang-1001.0.46.3)] 在 darwin 上键入“帮助”、“版权”、“学分”或“许可证”以获取更多信息。 >>> 打印(“\\”)\
  • 请看我提供的图片,在第三行我尝试了这个
  • 我知道了,我在打印时没有使用打印功能
猜你喜欢
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2012-04-22
  • 2016-08-30
  • 2017-06-13
  • 2019-09-18
  • 2013-11-10
相关资源
最近更新 更多