How would I go about parsing string literal segments in a string?

Question:

If I have a string like

'Hello, my name is "Bob" "I am 20 years old" I like to play "football"'

how would I go about parsing it in a way that gives me

["Bob", "I am 20 years old", "football"]

as a Python list?

Thanks!

Asked By: Omyy

||

Answers:

The python string.split() method allows you to specify a character that the string is divided by. The resulting array doesn’t remove the other content of the string, however you can use a quick for loop to select just the elements you’re interested in.

>>> a = 'Hello my name is "Bob" "I am 20 years old" I like to play "football"'
>>> b = a.split('"')
>>> b
['Hello my name is ', 'Bob', ' ', 'I am 20 years old', ' I like to play ', 'football', '']
>>> c = []
>>> for i in range(len(b)):
        if i%2 == 1:
            c.append(b[i])
>>> c
['Bob', 'I am 20 years old', 'football']

”’

Answered By: Benjamoomin64

Simply look for paired double quotes with anything except a double quote between them.

for match in re.finditer(r'"[^"]+"', text):
    print(match)
Answered By: tripleee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.