python split a string with special charcter
Question:
I need to split a string that I receive like that :
my_string = "datadetails350.23.43.txt"
when I use my_string.replace ("\", "/")
it returns : /data/detailsè.23.43.txt
It’s considering the 350
in my string as a special character 'è'
Answers:
in string literals are treated as escaping chars. That is why s1 = "linensecond line"
creates a string with two lines. That is also why you use "\"
in my_string.replace ("\", "/")
.
So to fix your problem, if you’re using a string literal my string = "datadetails350.23.43.txt"
you should instead use "\data\details\350.23.43.txt"
to make sure your
are properly escaped. Alternatively, you can use a raw string my string = r"datadetails350.23.43.txt"
by prepending r
to the quote. That way nothing gets escaped (so r"n"
would be a 2 char string with
and n
instead of just a single new line char)
Edit after your comment:
Try
my_string = r"datadetails350.23.43.txt"
That happens because ooo is interpreted as a character with octal value as described in the docs.
I guess the only way is to escape the as in:
my_string = "datadetails\350.23.43.txt"
Then you can do stuff like:
my_string.split("\")
Where do you get the string from? Is there a way to influence that?
And this looks like a path. It would be better to use
os.path.join("data", "details", "350.23.43.txt")
to create paths independently of the operating system.
I need to split a string that I receive like that :
my_string = "datadetails350.23.43.txt"
when I use my_string.replace ("\", "/")
it returns : /data/detailsè.23.43.txt
It’s considering the 350
in my string as a special character 'è'
in string literals are treated as escaping chars. That is why
s1 = "linensecond line"
creates a string with two lines. That is also why you use "\"
in my_string.replace ("\", "/")
.
So to fix your problem, if you’re using a string literal my string = "datadetails350.23.43.txt"
you should instead use "\data\details\350.23.43.txt"
to make sure your are properly escaped. Alternatively, you can use a raw string
my string = r"datadetails350.23.43.txt"
by prepending r
to the quote. That way nothing gets escaped (so r"n"
would be a 2 char string with and
n
instead of just a single new line char)
Edit after your comment:
Try
my_string = r"datadetails350.23.43.txt"
That happens because ooo is interpreted as a character with octal value as described in the docs.
I guess the only way is to escape the as in:
my_string = "datadetails\350.23.43.txt"
Then you can do stuff like:
my_string.split("\")
Where do you get the string from? Is there a way to influence that?
And this looks like a path. It would be better to use
os.path.join("data", "details", "350.23.43.txt")
to create paths independently of the operating system.