Rahul Kumar
Rahul Kumar

Reputation: 39

How can I make a string variable contain a single character "\" in python?

string="\"

This give error SyntaxError: EOL while scanning string literal

srring=r"\" also not working

Upvotes: 0

Views: 61

Answers (2)

Aiyion.Prime
Aiyion.Prime

Reputation: 1052

You could write it like this:

string="\\"

The first escapes the latter and prevents it from escaping the end of the literal.


Second question from the comments:

Write a function like this one:

def find(s, ch):
    return [i for i, ltr in enumerate(s) if ltr == ch]

then go and call it with your string:

s=r"w:/a\bc::/12\xy"
find(s, "\\")

which will print

[4, 12]

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522751

Just double up the backslash:

inp = "Jon\\Skeet"
print(inp)

This prints:

Jon\Skeet

The issue here is that backslash is a control character, and \" appearing inside a string delimited by double quotes means a literal double quote.

If you want to split the above string by backslash, then use split():

parts = inp.split("\\")
print(parts)

['Jon', 'Skeet']

Upvotes: 0

Related Questions