简体   繁体   中英

Split string by escape character

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

prefix your string with r - that will turn it into a raw string, telling python that \\ is a literal \\ .

s = r"C:\Users\as\Desktop\Data\pdf\txt\RTX_IDS_1DYS_20170610_0000_220279611-650000624200.txt"
parts = s.split("\\")
print(parts)

Output:

['C:', 'Users', 'as', 'Desktop', 'Data', 'pdf', 'txt', 'RTX_IDS_1DYS_20170610_0000_220279611-650000624200.txt']

For more information on string prefixes see:

https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM