首页 > 解决方案 > 除非在引号之间找到空格,否则使用空格作为分隔符在python中拆分字符串

问题描述

我想使用空格作为分隔符来拆分文本,除非在引号之间找到空格

例如

string = "my name is 'solid snake'"
output = ["my","name","is","'solid snake'"]

标签: pythonregex

解决方案


遍历字符串:

string = "my name is 'solid snake'"
quotes_opened = False
out = []
toadd = ''
for c, char in enumerate(string):
    if c == len(string) - 1: #is the character the last char
        toadd += char
        out.append(toadd); break
    elif char in ("'", '"'): #is the character a quote
        if quotes_opened:
            quotes_opened = False #if quotes are open then close
        else:
            quotes_opened = True #if quotes are closed the open
        toadd += char
    elif char != ' ':
        toadd += char #add the character if it is not a space
    elif char == ' ': #if character is a space
        if not quotes_opened: #if quotes are not open then add the string to list
            out.append(toadd)
            toadd = ''
        else: #if quotes are still open then do not add to list
            toadd += char
print(out)

推荐阅读