Python splits string with space if a \ is not in front

Sorry if this post is a bit confusing to read this is my first post on this site and this is the difficult question I asked, I tried my best. I also tried Google search and I can not find anything.

I am trying to make my own command line as an application in python, and I would like to know how to split the line if "\" is not in front of the space and removes the backslash.

This is what I mean.

>>> c = "play song I\ Want\ To\ Break\ Free"
>>> print c.split(" ")
['play', 'song', 'I\\', 'Want\\', 'To\\', 'Break\\', 'Free']

When I break cinto a space, it retains the backslash, but removes the space. This is how I want it to be like this:

>>> c = "play song I\ Want\ To\ Break\ Free"
>>> print c.split(" ")
['play', 'song', 'I ', 'Want ', 'To ', 'Break ', 'Free']

If someone can help me, it will be great!

Also, if you need regular expressions, you could explain this more, because I have never used them before.

Edit: , , , ?

+4
2

, . , shlex.split? lexing . :

>>> import shlex
>>> shlex.split('play song I\ Want\ To\ Break\ Free')
['play', 'song', 'I Want To Break Free']
+6

, , , :

[s[:-1] + ' ' if s.endswith('\\') else s for s in c.split(' ')]

; c , \ ; , .

: ( ), .

:

>>> c = r"play song I\ Want\ To\ Break\ Free"
>>> [s[:-1] + ' ' if s.endswith('\\') else s for s in c.split(' ')]
['play', 'song', 'I ', 'Want ', 'To ', 'Break ', 'Free']

escape- , . , :

[s[:-1] + ' ' if s.endswith('\\') and (len(s) - len(s.rstrip('\\'))) % 2 == 1 else s
 for s in c.split(' ')]

:

>>> c = r"play song I\ Want\ To\ Break\\ Free"
>>> [s[:-1] + ' ' if s.endswith('\\') and (len(s) - len(s.rstrip('\\'))) % 2 == 1 else s
...  for s in c.split(' ')]
['play', 'song', 'I ', 'Want ', 'To ', 'Break\\\\', 'Free']
+2

Source: https://habr.com/ru/post/1537121/


All Articles