按转义字符拆分字符串

Split string by escape character

我正在尝试通过 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

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