I would like to split a text using space as the delimiter unless the space is found between quotation marks
for example
string = "my name is 'solid snake'"
output = ["my","name","is","'solid snake'"]
I would like to split a text using space as the delimiter unless the space is found between quotation marks
for example
string = "my name is 'solid snake'"
output = ["my","name","is","'solid snake'"]
Looping through the string:
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)
A brute force way would be:
string = "my name is 'solid snake'"
output = ["my","name","is","'solid snake'"]
ui= "__unique__"
string2= string.split("'")
print(string2)
for i, segment in enumerate(string2):
if i %2 ==1:
string2[i]=string2[i].replace(" ",ui)
print(string2)
string3= "'".join(string2)
print(string3)
string4=string3.split(" ")
print(string4)
for i, segment in enumerate(string4):
if ui in segment:
string4[i]=string4[i].replace("__unique__", " ")
print()
print(string4)