pythonevaluate

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)

Solution

  • 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))