简体   繁体   中英

Filter out a specific string in a larger string?

I'm new to Python and after this one script I probably won't work with Python at all. I'm extracting some data using Scrapy and have to filter out some string (I've already done this with digits using isdigit()). Googling gives me pages about filtering out special strings, but what I want is really just a small part of a larger string.

This is the string:

Nima Python: how are you?

What I want left:

how are you?

so this part removed:

Nima Python:

Thanks in advance guys.

I'm assuming there will be other strings like this... so I'm guessing str.split() might be a good bet.

>>> string = "Nima Python: how are you (ie: what's wrong)?"
>>> string.split(': ')
['Nima Python', 'how are you (ie', " what's wrong)?"]
>>> string.split(': ', 1)[1]
"how are you (ie: what's wrong)?"

This works:

>>> s = "Nima Python: how are you?"
>>> s.replace("Nima Python: ", "") # replace with empty string to remove
'how are you?'
>>> string = 'Nima Python: how are you?'
>>> string.split(':')[1].strip()
'how are you?'

String slicing: (This is the easiest way, but isn't very flexible)

>>> string = "Nima Python: how are you?"
>>> string
'Nima Python: how are you?'
>>> string[13:] # Used 13 because we want the string from the 13th character
'how are you?'

String replace:

>>> string = "Nima Python: how are you?"
>>> string.replace("Nima Python: ", "")
'how are you?'

String split: (splitting the string into two parts using the ":")

>>> string = "Nima Python: how are you?"
>>> string.split(":")[1].strip()
'how are you?'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM