1

I want to use a backslash in Python, but I always get an error. This is my code

fileName = "file"
linkName = "rep\" + file_name
print(linkName)

The error: SyntaxError: EOL while scanning string literal

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Niku
  • 91
  • 6

1 Answers1

1

The error is simple. Just had the same Use this:

fileName = "file"
linkName = "rep" + chr(92) + file_name
print(linkName)

chr(92) stands for \

  • It works in every projects for me –  Apr 16 '21 at 16:45
  • 1
    Yes, it *works*, but there are other solutions that don't require the reader to consult an ASCII chart to make sense of the code... – jasonharper Apr 16 '21 at 16:50
  • Not my downvote but just because it works doesn’t make it good code: it’s unnecessarily convoluted. The correct (= widely accepted as standard, more readable, more efficient …) solution is to escape the backslash. There’s no reason whatsoever to use `chr` here. – Konrad Rudolph Apr 16 '21 at 16:50
  • Yeah, in my case it works using "\\" instead of "\" and it's more readable. – V-cash May 13 '21 at 14:18