Reputation: 175
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.
Upvotes: 1
Views: 440
Reputation: 86
Two things.
First, with regards to the EOL error, my best guess - without access to the actual python session - is that python was complaining because you have an unterminated string caused by the final "
character being escaped, which will happend even if the string is prefixed with r
. My opinion is that you should drop the prefix and just correctly espace all backslashes like so: \\
.
In your example, path
then becomes path = "C:\\folder\\whatever\\"
Secondly, instead of manually concatenating paths, you should use os.path.join:
import os
mystring = "blablabla"
path = "C:\\folder\\whatever"
print os.path.join(path, mystring)
## prints C:\\folder\\whatever\\blablabla
Note that os.path
will use the path convetions for the operating system where the application is running, so the above code will produce erroneous/unexpected results if you run it on, say, Linux. Check the notes on the top of the page that I have linked for details.
Upvotes: 1
Reputation: 73186
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
Upvotes: 1
Reputation: 85482
Always use os.path.join()
to join paths and the r
prefix to allow single back slashes as Windows path separators:
r"C:\folder\whatever"
Now, now trailing back slash is needed:
>>> import os
>>> mystring = "blablabla"
>>> path = r"C:\folder\whatever"
>>> os.path.join(path, mystring)
'C:\\folder\\whatever\\blablabla'
Upvotes: 2