Python Complex String Separation

Say I have this line:

"hello":"noun":"a greeting";"hello":"verb":"the;action;of;greeting"

How can I make string.split (";") or string.split (":") ignore any quoted characters?

Thanks PM

0
source share
2 answers

If you cannot get a cleaner input than this, I would recommend using a regex and creating listfrom tuplewith findall():

>>> import re
>>> mystring = '"hello":"noun":"a greeting";"hello":"verb":"the;action;of;greeting"'
>>> result = re.findall(r'"(.+?)":"(.+?)":"(.+?)"', mystring)
>>> for item in result:
...     print(*item)
...
hello noun a greeting
hello verb the;action;of;greeting

You can format the output with str.format():

>>> for item in result:
...     print('{} - {}, {}'.format(*(part.replace(';', ' ') for part in item)))
...
hello - noun, a greeting
hello - verb, the action of greeting
+3
source

100% , . , . ( , ).

In [20]: [x for x in re.split(r'(:|;|".*?")', s) if x not in [":",";",""]]
Out[20]:
['',
 '"hello"',
 '"noun"',
 '"a greeting"',
 '"hello"',
 '"verb"',
 '"the;action;of;greeting"']
0

All Articles