Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to Python string replace method

Tags:

python

string

I want to delete certain words from a paragraph, such as "and", "as", and "like". Is there an easier way to delete words from a string than doing it via replace --

new_str = str.replace(' and ', '').replace(' as ', '').replace(' like ', '')

For example, is there a method similar to the following?

str.remove([' and ', ' like ', ' as '])

like image 775
David542 Avatar asked Dec 04 '11 04:12

David542


1 Answers

Yes, you could use the sub function from the re module:

>>> import re
>>> s = 'I like this as much as that'
>>> re.sub('and|as|like', '', s)
'I  this  much  that'
like image 149
juliomalegria Avatar answered Sep 27 '22 01:09

juliomalegria