[英]How to make a single backslash string
I'd like to make a list which is literally this: '\\'
.我想列出一个字面意思是: '\\'
。 But doing string = '\\'
raises an EOL SyntaxError.但是执行string = '\\'
会引发 EOL SyntaxError。 How would I do it?我该怎么做?
Many answers say to do string = '\\\\'
but then when I print the string it shows as '\\\\'
not '\\'
许多答案说要执行string = '\\\\'
但是当我打印字符串时,它显示为'\\\\'
而不是'\\'
EDIT 1 This used to be about a list containing a string ( ['\\']
rather than '\\'
).编辑 1这曾经是一个包含字符串( ['\\']
而不是'\\'
)的列表。 But I realised the list was not the issue.但我意识到列表不是问题。 That's why some of the answers talk about a list.这就是为什么一些答案谈论列表的原因。
EDIT 2 This is a vscode notebook issue!编辑 2这是一个 vscode 笔记本问题! More edit It doesn't happen in a standard Jupyter notebook.更多编辑它不会发生在标准的 Jupyter 笔记本中。 Even when I try to write string = '\\\\'
to a file rather than just print it, it comes out as '\\\\'
即使我尝试将string = '\\\\'
写入文件而不只是打印它,它也会显示为'\\\\'
The simplest solution to this problem is to use two backslashes: \\\\
.解决此问题的最简单方法是使用两个反斜杠: \\\\
。 This way, Python sees the first backslash and interprets the second one literally.这样,Python 会看到第一个反斜杠并按字面解释第二个反斜杠。
ls = ['\\']
Edit :编辑 :
If you're asking for double backslash then :如果您要求使用双反斜杠,则:
ls = [r'\\']
It is called raw string.它被称为原始字符串。
Edit on question :编辑问题:
You should use this:你应该使用这个:
string=r'\\'
You can use double backslashes.您可以使用双反斜杠。 Imagine that second one negates it.想象第二个否定它。
ls = ['\\']
The character \\
is an escape character.字符\\
是转义字符。 I means the character after \\
is not considered as a meaningful character. I 的意思是\\
之后的字符不被视为有意义的字符。
For example if you want to put a "
in a string you can do it by:例如,如果您想在字符串中放置一个"
,您可以通过以下方式实现:
string = "There is a \" in my text"
So you should escape \\ inside the string.所以你应该在字符串中转义 \\ 。
tl;dr tl;博士
the_list = ["\\"]
You can bypass Python string interpolation logic using chr(chr_number)
In this case 92
:您可以使用chr(chr_number)
在这种情况下绕过 Python 字符串插值逻辑92
:
>>> li=[chr(92)]
>>> li
['\\'] # that is a SINGLE character of '\'
Then use *
to make it any length:然后使用*
使其任意长度:
>>> s=chr(92)*3
>>> s
'\\\\\\'
>>> len(s)
3
And it works in f
strings as you may want:它可以根据需要在f
字符串中工作:
>>> f'{chr(92)}'
'\\'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.