123456
123456

Reputation: 145

Python eval: SyntaxError: unexpected character after line continuation character

I want to evaluate a string of a file path to open the file, but I get the error:
File :1 'C:\Users\xxx\Desktop_Revenue\Input' + str(yr) + '\' + 'Survey' + YY + '_revenue.xlsx'

SyntaxError: unexpected character after line continuation character

The syntax error is at '\'

I want to use eval as my file path is passed into a function later


url= " 'C:\\Users\\xxx\\Desktop\\_Revenue\\Input\\'  + str(yr) + '\\' + 'Survey' + YY + '_revenue.xlsx'"

def test (yr):
   yr=yr
   YY=str(yr)[2:]

   survey_url= eval(url)

test(2015)

Upvotes: -1

Views: 76

Answers (2)

weasel
weasel

Reputation: 574

Use f-strings for a more intuitive way to pass variables in strings, and r-strings to handle \\

url= rf"C:\\Users\\xxx\\Desktop\\_Revenue\\Input\\{yr}\\Survey{YY}_revenue.xlsx"

Upvotes: 0

Mark Tolonen
Mark Tolonen

Reputation: 177961

eval is nearly always the wrong answer. If you want to re-use a format string, use .format() to pass variables to an unprocessed format string:

# raw string to skip escaping backslashes.
# unprocessed format string (use .format later)
URL = r'C:\Users\xxx\Desktop\_Revenue\Input\{yr}\Survey{YY}_revenue.xlsx'

def test(yr):
    YY = yr % 100
    # ** passes a dictionary argument as named parameters.
    # locals() is a dictionary of the local variables, e.g.
    # {'yr': 2024, 'YY': 24}.
    return URL.format(**locals())

print(test(2015))
print(test(2024))

Output:

C:\Users\xxx\Desktop\_Revenue\Input\2015\Survey15_revenue.xlsx
C:\Users\xxx\Desktop\_Revenue\Input\2024\Survey24_revenue.xlsx

Another version without the **locals() trickery:

URL = r'C:\Users\xxx\Desktop\_Revenue\Input\{0}\Survey{1}_revenue.xlsx'

def test(yr):
    YY = yr % 100
    return URL.format(yr, YY)  # {0} is first parameter to format, {1} the 2nd, etc.

print(test(2015))
print(test(2024))

Upvotes: 1

Related Questions