Home > database >  Split string on backlash with trailing number
Split string on backlash with trailing number

Time:01-31

I've got a string that I need to split. I've tried various split/replace methods but the trailing '\03' is treated like an octal '\x03', so most of the 'usual' ways didn't work for me.

I've eventually come up with the following (which works, aside from the extra single quotation marks which I can easily remove) but I feel there must be a better/simpler way of doing this?

I have read a from a file.

import re
a = "Delimited\string\03"
n = a.replace('\\', '-')
e = repr(n).replace('\\x', '-')
x = re.split('-', e)
print(x) # Gives: ["'Delimited", 'string', "03'"]

More info:

I was just testing/developing without reading from an actual file. Ultimately a will come from a file.

a = 'Delimited\string\03'
print(a)
print(a.split("\\"))

The above gives ['Delimited', 'string\x03']. When I read from a file using the minimal example given in the answers, it works fine. I don't understand then why reading from file gives a different result because when I read from file a is Delimited\string\03 from print(a) above?? So why does Python treat it differently?

CodePudding user response:

This has worked for me, but it was already mentioned from Brad Solomon

t = r"Delimited\string\03"
print(t.split("\\"))

Good luck :)

CodePudding user response:

And this doesn't work?
Untitled.txt: Delimited\string\03
Code:

a = open("Untitled.txt", "r").read()
print(a.split("\\"))

Output: ['Delimited', 'string', '03']

  •  Tags:  
  • Related