pythonsplitshlex

Preserve "\t", "\n", "\r" when spliting a string using shlex in python


I am trying to split a string using shlex but I want to preserve(literally) "\t", "\n", "\r".

Example:

text = "a=\t\n\r\example c=d"
sp_text = shlex.split(text)
print(sp_text)

['a=', 'example', 'c=d']

But I want to print this:

['a=\t\n\r\example', 'c=d']

Can I do that using shlex?

/Angelos


Solution

  • You could do the following:

    import shlex
    
    text = "a=\t\n\r\example c=d"
    
    sh = shlex.shlex(text)
    sh.whitespace = ' '
    sh.whitespace_split = True
    
    sp_text = list(sh)
    print(sp_text)
    

    Output

    ['a=\t\n\r\\example', 'c=d']
    

    Notice that the example above only uses the single whitespace for splitting, the idea of the example is to illustrate how to manipulate the shlex whitespace.