Ich muss ein bestimmtes Wort aus einer Zeichenfolge entfernen.
Aber ich finde, Python-Strip-Methode scheint ein geordnetes Wort nicht zu erkennen. Das entfernt einfach alle Zeichen, die an den Parameter übergeben werden.
Zum Beispiel:
>>> papa = "papa is a good man"
>>> app = "app is important"
>>> papa.lstrip('papa')
" is a good man"
>>> app.lstrip('papa')
" is important"
Wie kann ich ein bestimmtes Word mit Python entfernen?
Verwenden Sie str.replace
.
>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'
Verwenden Sie alternativ re
und verwenden Sie reguläre Ausdrücke. Dadurch können führende/nachgestellte Leerzeichen entfernt werden.
>>> 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'
Am einfachsten wäre es, ihn einfach durch eine leere Zeichenfolge zu ersetzen.
s = s.replace('papa', '')
Sie können auch einen Regex mit re.sub
verwenden:
article_title_str = re.sub(r'(\s?-?\|?\s?Times of India|\s?-?\|?\s?the Times of India|\s?-?\|?\s+?Gadgets No'',
article_title_str, flags=re.IGNORECASE)
Vorausgesetzt, Sie kennen den Indexwert des Beginns und des Endes jedes Words, das Sie im Zeichen-Array ersetzen möchten, und möchten nur diesen bestimmten Datenblock ersetzen, könnten Sie dies so tun.
>>> s = "papa is papa is papa"
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(s)
papa is mama is papa
Wenn Sie die ursprüngliche Datenstruktur auch beibehalten möchten, können Sie sie alternativ in einem Wörterbuch speichern.
>>> bin = {}
>>> s = "papa is papa is papa"
>>> bin["0"] = s
>>> s = s[:8]+s[8:13].replace("papa", "mama")+s[13:]
>>> print(bin["0"])
papa is papa is papa
>>> print(s)
papa is mama is papa