I need to strip a specific word from a string.
But I find python strip method seems can't recognize an ordered word. The just strip off any characters passed to the parameter.
For example:
>>> papa = "papa is a good man" >>> app = "app is important" >>> papa.lstrip('papa') " is a good man" >>> app.lstrip('papa') " is important"
How could I strip a specified word with python?
Python String strip()The strip() method returns a copy of the string by removing both the leading and the trailing characters (based on the string argument passed).
Remove a Word from String using replace() print("Enter String: ", end="") text = input() print("Enter a Word to Delete: ", end="") word = input() wordlist = text. split() if word in wordlist: text = text.
String has a contains() method - you can use that. Is String. indexOf() available in android?
Use str.replace
.
>>> papa.replace('papa', '') ' is a good man' >>> app.replace('papa', '') 'app is important'
Alternatively use re
and use regular expressions. This will allow the removal of leading/trailing spaces.
>>> import re >>> papa = 'papa is a good man' >>> app = 'app is important' >>> papa3 = 'papa is a papa, and papa' >>> >>> patt = re.compile('(\s*)papa(\s*)') >>> patt.sub('\\1mama\\2', papa) 'mama is a good man' >>> patt.sub('\\1mama\\2', papa3) 'mama is a mama, and mama' >>> patt.sub('', papa3) 'is a, and'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With