Alexander Soare
Alexander Soare

Reputation: 3247

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. 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 '\\'

Upvotes: 2

Views: 3232

Answers (4)

niaei
niaei

Reputation: 2399

TL;DR

the_list = ["\\"]

Explanation:

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.

Upvotes: 1

dawg
dawg

Reputation: 103814

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)}'
'\\'

Upvotes: 4

imxitiz
imxitiz

Reputation: 3987

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'\\'

Upvotes: 2

franzmaliszt
franzmaliszt

Reputation: 41

You can use double backslashes. Imagine that second one negates it.

ls = ['\\']

Upvotes: 1

Related Questions