Search code examples
python-2.7split

Split string at delimiter '\' in python


I have a quick question. I am trying to split a string S : 'greenland.gdb\topology_check\t_buildings' at '\' using:

     S.split('\')

I expect output list :

 ['greenland.gdb', 'topology_check', 't_buildings']. 

Instead it returns error : SyntaxError: EOL while scanning string literal. What is with character '\' in python. With any other character it works fine.


Solution

  • You need to escape the backslash:

     S.split('\\')
    

    You may also need to string_escape:

    In [10]: s = 'greenland.gdb\topology_check\t_buildings'
    
    In [11]: s.split("\\")
    Out[11]: ['greenland.gdb\topology_check\t_buildings']
    
    In [12]: s.encode("string_escape").split("\\")
    Out[12]: ['greenland.gdb', 'topology_check', 't_buildings']
    

    \t would be interpreted as a tab character unless you were using a raw string:

    In [18]: s = 'greenland.gdb\topology_check\t_buildings'
    
    In [19]: print(s)
    greenland.gdb   opology_check   _buildings
    
    In [20]: s = r'greenland.gdb\topology_check\t_buildings'
    
    In [21]: print(s)
    greenland.gdb\topology_check\t_buildings
    

    Escape characters