0 votes
1 view
in Python by (17k points)

I'm trying to split a string by the escape character in Python.

This is the way I've been trying to do it:

s = "C:\Users\as\Desktop\Data\pdf\txt\RTX_IDS_1DYS_20170610_0000_220279611-650000624200.txt"

s.encode("string_escape").split("\\")

When I run it, I get the following error:

s = "C:\Users\as\Desktop\Data\pdf\txt\RTX_IDS_1DYS_20170610_0000_220279611-650000624200.txt"

       ^

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

1 Answer

0 votes
by (25.1k points)

You can prefix your string with r so that python will treat that string as a raw string and take the backslashes '\' as literal backslashes and not escape characters. Like this:

s = r"C:\Users\as\Desktop\Data\pdf\txt\RTX_IDS_1DYS_20170610_0000_220279611-650000624200.txt"

parts = s.split("\\")

print(parts)

Related questions

0 votes
1 answer
asked Jul 18, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Oct 3, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 10, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...