Reputation: 1301
How to remove all characters outside quotation mark for example this is my string
message = 'something "like" this'
print( removeFromQuote(message) )
message2 = 'something "like this" thank you!'
print( removeFromQuote(message2) )
then the result :
like
like this
how to create a function removeFromQuote that can do this.
or using re.sub with the correct regex
thank you in advance!
Upvotes: 2
Views: 852
Reputation: 2320
You can use regular expressions:
import re
def removeFromQuote(message):
return re.findall(r'"(.+?)"', message)
Here is the result:
>>> message = 'something "like this" or "like that"'
>>> removeFromQuote(message)
['like this', 'like that']
Upvotes: 1
Reputation: 71610
Try using findall
:
import re
message = 'something "like this" thank you'
print(re.findall('"(\D+)"',message)[0])
Output:
like this
Upvotes: 4
Reputation: 184395
First, split the string on quotes.
message = 'something "like" this'
chunks = message.split('"')
The elements of the list that are bits of the text inside the quotes are the odd-numbered ones. So just get those.
odd_chunks = chunks[1::2]
Now join the list back together into a string.
result = "".join(odd_chunks)
Putting it all together:
def removeFromQuote(text):
return "".join(text.split('"')[1::2])
Upvotes: 1