Using Split() in Python to pull all the quotes out of a string

3123 views python
2

So what I'm trying to do is use python to parse through articles on pull all the quotes. I used beautiful soup to pull the html from the site, now I'm trying to use split to print everything that is in quotes.

For example, go from:

I like quotes but especially "have problems"

to go to

have problems

answered question

3 Answers

10

It's probably better to use a regular expression rather than split:

import re

s = 'I like quotes but especially "have problems"'    

>>> re.findall('"(.*)"',s)
['have problems']

posted this
0

You can slice the list returned by str.split:

s = 'I like quotes but especially "have problems" and "need more quotes"'
s.split('"')[1::2]

This returns:

['have problems', 'need more quotes']

posted this
8

Or re.findall(r'"([^"]*)"',s), demo:

>>> import re
>>> s='I like quotes but especially "have problems"'
>>> re.findall(r'"([^"]*)"',s)
['have problems']
>>> 

regex is your clear friend,

https://docs.python.org/3/howto/regex.html

https://docs.python.org/3/library/re.html?highlight=findall#re.findall

posted this

Have an answer?

JD

Please login first before posting an answer.