I have string variable which is
temp = '1\2\3\4'
I would like to add a prefix 'r' to the string variable and get
r'1\2\3\4'
so that I can split the string based on '\'. I tried the following:
r'temp'
'r' + temp
r + temp
But none of the above works. Is there a simple to do it? I'm using python 3. I also tried to encode the string, using
temp.encode('string-escape')
But it returns the following error
LookupError: unknown encoding: string-escape
r
is a prefix for string literals. This means, r"1\2\3\4"
will not interpret \
as an escape when creating the string value, but keep \
as an actual character in the string. Thus, r"1\2\3\4"
will have seven characters.
You already have the string value: there is nothing to interpret. You cannot have the r
prefix affect a variable, only a literal.
Your temp = "1\2\3\4"
will interpret backslashes as escapes, create the string '1\x02\x03\x04'
(a four-character string), then assign this string to the variable temp
. There is no way to retroactively reinterpret the original literal.
EDIT: In view of the more recent comments, you do not seem to, in fact, have a string "1\2\3\4"
. If you have a valid path, you can split it using
path.split(r'\')
or
path.split('\\')
but you probably also don't need that; rather, you may want to split a path into directory and file name, which is best done by os.path
functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With