[Python] Python split string with space unless a \ is in front

Discussão em 'Python' iniciado por Stack, Junho 4, 2025.

  1. Stack

    Stack Membro Participativo

    Sorry if this post is a bit confusing to read this is my first post on this site and this is a hard question to ask, I have tried my best. I have also tried googling and i can not find anything.

    I am trying to make my own command line like application in python and i would like to know how to split a string if a "\" is not in front of a space and to delete 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 split c with a space it keeps the backslash however it removes the space. This is how I want it to be like:

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


    If someone can help me that would be great!

    Also if it needs Regular expressions could you please explain it more because I have never used them before.

    Edit: Now this has been solved i forgot to ask is there a way on how to detect if the backslash has been escaped or not too?

    Continue reading...

Compartilhe esta Página