Tag Archives: python SyntaxError: EOL while scanning string literal

How to Solve Python SyntaxError: EOL while scanning string literal

The cause of the error is that the string ends in or the string is missing quotation marks

This error occurs when writing code to splice windows path. Only by looking up the data can we know that the string in Python cannot end with \

My code is as follows

import os
dirname = "test"

path = r'C:\Users\panda\Desktop\newfile\' + dirname

When running, an error will be reported

File "test.py", line 3
    path = r'C:\Users\panda\Desktop\newfile\' + dirname
                                                    ^
SyntaxError: EOL while scanning string literal

So how to solve it

Method 1: use os.path.join

path = os.path.join(r'C:\Users\panda\Desktop\newfile', dirname)

Method 2: the backslash of the path uses escape instead of R

path = 'C:\\Users\\panda\\Desktop\\newfile\\' + dirname

Method 3: format string

dirname="test"
path = r'C:\Users\panda\Desktop\newfile\%s' % (dirname)  # The first formatting method
#从 python 2.6 start
path = r'C:\Users\panda\Desktop\newfile\{}'.format(dirname) # The second formatting method

Method 4: String interpolation

Support string interpolation from Python 3.6

# python 3.6 support string interpolation
dirname = "test"
path3 = rf'C:\Users\panda\Desktop\newfile\{dirname}' 

Reference: https://docs.python.org/3/whatsnew/3.6.html#whatsnew36 -pep498

Why can’t a string end with a (backslash)

Because backslashes have other uses. In Python, when a complete string is too long, a line cannot be written and you want to wrap it. However, if you want to keep it as a string, you can wrap it with a backslash. Therefore, the backslash cannot be immediately followed by the quotation mark at the end of the string

The following is a demonstration with repl