0

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
Alan
  • 129
  • 1
  • 13
  • Possible duplicate of [How to split a dos path into its components in Python](https://stackoverflow.com/questions/3167154/how-to-split-a-dos-path-into-its-components-in-python) – Error - Syntactical Remorse Jul 12 '19 at 13:03

1 Answers1

5

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

Mike Scotty
  • 10,530
  • 5
  • 38
  • 50
  • Thanks!! Also I'm iterating a list of strings. Is there a way to convert them to raw strings? How would it be possible to add the `r` in front of the string? – Alan Jul 12 '19 at 12:44
  • 1
    You only need the prefix for string literals (and you cannot add a prefix afterwards). If you have filled a str variable programmatically, special characters are already escaped internally, so no need for a prefix. You can check the escaping with ``repr``, example: ``print(repr(r"C:\users"))`` Output: ``'C:\\users'`` – Mike Scotty Jul 12 '19 at 12:50