0

I want to add a backslash to a list in Python but it gives an error.

Output:

chars = [".", ",", "/", "\"]
                        ^
SyntaxError: unterminated string literal (detected at line 8)
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Kuzey Bro
  • 9
  • 1
  • 7
    this is an escape character. you can either replace with `"\\"` or `r"\"` – jsofri Jul 24 '22 at 08:43
  • 1
    Also related: [How to print a single backslash?](https://stackoverflow.com/q/19095796/2745495) – Gino Mempin Jul 24 '22 at 08:49
  • 3
    @jsofri `r"\"` still won't work. – Lecdi Jul 24 '22 at 08:50
  • 1
    If you are only using the list to iterate over / check if characters are in it, you probably don't need a list. A string supports all of those operations, so you can just store the characters in a string `".,/\\"`. – Lecdi Jul 24 '22 at 08:51

2 Answers2

0

Backslashes allow you to enter characters that are normally used by the code, eg. " and '. To avoid the problem, simply just add another back slash. "\" -> "\\"

0

It is giving an error because \ is an escape character, You can store this using escaping this another escape character

chars = [".", ",", "/", "\\"]
Sidharth Mudgil
  • 1,293
  • 8
  • 25