String.replace () ist in Python 3.x veraltet. Was ist der neue Weg, dies zu tun?
String.replace () ist in Python 3.x veraltet. Was ist der neue Weg, dies zu tun?
Antworten:
Wie in 2.x Verwendung str.replace()
.
Beispiel:
>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
re.sub()
.
string
Funktionen sind veraltet. str
Methoden sind nicht.
'foo'.replace(...)
Die replace () -Methode in Python 3 wird einfach verwendet von:
a = "This is the island of istanbul"
print (a.replace("is" , "was" , 3))
#3 is the maximum replacement that can be done in the string#
>>> Thwas was the wasland of istanbul
# Last substring 'is' in istanbul is not replaced by was because maximum of 3 has already been reached
Sie können str.replace () als Kette von str.replace () verwenden . Denken Sie, Sie haben eine Zeichenfolge wie 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
und möchten alle '#',':',';','/'
Zeichen durch ersetzen '-'
. Sie können es entweder auf diese Weise ersetzen (normaler Weg),
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'
>>> str = str.replace('#', '-')
>>> str = str.replace(':', '-')
>>> str = str.replace(';', '-')
>>> str = str.replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
oder auf diese Weise (Kette von str.replace () )
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
Zu Ihrer Information: Wenn Sie einige Zeichen an ein beliebiges, positionsfestes Wort innerhalb der Zeichenfolge anhängen (z. B. Ändern eines Adjektivs in ein Adverb durch Hinzufügen des Suffix -ly ), können Sie das Suffix zur besseren Lesbarkeit am Ende der Zeile einfügen. Verwenden Sie dazu split()
inside replace()
:
s="The dog is large small"
ss=s.replace(s.split()[3],s.split()[3]+'ly')
ss
'The dog is largely small'
ss = s.replace(s.split()[1], +s.split()[1] + 'gy')
# should have no plus after the comma --i.e.,
ss = s.replace(s.split()[1], s.split()[1] + 'gy')