String.replace () è deprecato su python 3.x. Qual è il nuovo modo di farlo?
String.replace () è deprecato su python 3.x. Qual è il nuovo modo di farlo?
Risposte:
Come in 2.x, utilizzare str.replace().
Esempio:
>>> 'Hello world'.replace('world', 'Guido')
'Hello Guido'
re.sub(),.
stringfunzioni sono obsolete. stri metodi non lo sono.
'foo'.replace(...)
Il metodo replace () in python 3 è usato semplicemente da:
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
Puoi usare str.replace () come una catena di str.replace () . Pensa di avere una stringa simile 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'e vuoi sostituire tutto il '#',':',';','/'segno con '-'. Puoi sostituirlo in questo modo (modo normale),
>>> 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)'
o in questo modo (catena di str.replace () )
>>> str = 'Testing PRI/Sec (#434242332;PP:432:133423846,335)'.replace('#', '-').replace(':', '-').replace(';', '-').replace('/', '-')
>>> str
'Testing PRI-Sec (-434242332-PP-432-133423846,335)'
Cordiali saluti, quando si aggiungono alcuni caratteri a una parola arbitraria, fissa nella posizione all'interno della stringa (ad esempio, cambiando un aggettivo in un avverbio aggiungendo il suffisso -ly ), è possibile mettere il suffisso alla fine della riga per leggibilità. Per fare questo, usa split()dentro 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')