I'd like to make a list which is literally this: '\\'
. But doing string = '\\'
raises an EOL SyntaxError. How would I do it?
Many answers say to do string = '\\\\'
but then when I print the string it shows as '\\\\'
not '\\'
EDIT 1 This used to be about a list containing a string ( ['\\']
rather than '\\'
). 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! More edit It doesn't happen in a standard Jupyter notebook. Even when I try to write string = '\\\\'
to a file rather than just print it, it comes out as '\\\\'
The simplest solution to this problem is to use two backslashes: \\\\
. This way, Python sees the first backslash and interprets the second one literally.
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.
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
the_list = ["\\"]
You can bypass Python string interpolation logic using chr(chr_number)
In this case 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'{chr(92)}'
'\\'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.