Home > Software engineering >  How would I go about parsing string literal segments in a string?
How would I go about parsing string literal segments in a string?

Time:08-27

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!

CodePudding user response:

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

for match in re.finditer(r'"[^"] "', text):
    print(match)

CodePudding user response:

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']

'''

  • Related