用转义符分割字符串

时间:2019-07-12 12:29:29

标签: python split unicode-escapes

我正在尝试用Python中的转义字符分割字符串。

这是我一直在尝试的方法:

s = "C:\Users\as\Desktop\Data\pdf\txt\RTX_IDS_1DYS_20170610_0000_220279611-650000624200.txt"
s.encode("string_escape").split("\\")

运行它时,出现以下错误:

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 个答案:

答案 0 :(得分:5)

r前缀您的字符串-它将变成原始字符串,告诉python \是文字\

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

输出:

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

有关字符串前缀的更多信息,请参见:

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