Search code examples
pythonstringconcatenationeol

EOL while concatenating string + path


I need to concatenate specific folder path with a string, for example:

mystring = "blablabla"
path = "C:\folder\whatever\"

printing (path + mystring) should return: C:\folder\whatever\blablabla

However I always get the EOL error, and it's a must the path to have the slash like this: \ and not like this: /

Please show me the way, I tried with r' it's not working, I tried adding double "", nothing works and I can't figure it out.


Solution

  • Either use escape character \\ for \:

    mystring = "blablabla"
    path = "C:\\folder\\whatever\\"
    
    conc = path + mystring
    print(conc)
    # C:\folder\whatever\blablabla
    

    Or, make use of raw strings, however moving the last backslash from end of path to the start of myString:

    mystring = r"\blablabla"
    path = r"C:\folder\whatever"
    
    conc = path + mystring
    print(conc)
    # C:\folder\whatever\blablabla
    

    The reason why your own raw string approach didn't work is that a raw strings may not end with a single backslash:

    Specifically, a raw literal cannot end in a single backslash (since the backslash would escape the following quote character).

    From