-2

I need to split a string that I receive like that :

my_string = "\data\details\350.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 'è'

sevenfold
  • 101
  • 8

2 Answers2

1

\ in string literals are treated as escaping chars. That is why s1 = "line\nsecond 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 = "\data\details\350.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"\data\details\350.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)

Faboor
  • 1,365
  • 2
  • 10
  • 23
1

Edit after your comment: Try

my_string = r"\data\details\350.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 = "\data\details\\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.

bechtold
  • 446
  • 3
  • 14