Search code examples
pythonsplitunicode-escapes

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

Solution

  • 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