简体   繁体   English

用转义符分割字符串

[英]Split string by escape character

I'm trying to split a string by the escape character in Python. 我正在尝试用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 \\ . 给您的字符串加上r前缀-它将变成原始字符串,告诉python \\是文字\\

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 https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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