-4

I wanted to find the character \ in a string but this also happens to be the character for escaping so when i use string1.find("\") it doesn't work due to the backslash not letting the " close off the string.

If I add a trailing space, the error is fixed, however then it will not find just the backslash.

How can I put the backslash character \ inside a string can still close it.

john hon
  • 103
  • 2
  • 2
  • 7

1 Answers1

1

The way to write a string literal containing a single backslash (and nothing else) is '\\'.

This works in just the same way as '\'' is a string literal containing one single quote (and nothing else). \ + char => a single character. What is confusing you is that if the character is not one of the recognized escaping characters (' " n \, etc) then both the backslash and the character are left in the string.

C:\>python Python 3.4.2 (v3.4.2:ab2c023a9432, Oct  6 2014, 22:16:31)
[MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> '\\'
'\\'
>>> '\ '
'\\ '
>>>

Note how the second string is displayed with the backslash escaped.