English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode replace() remplace old (l'ancien chaîne de caractères) par new (nouveau chaîne de caractères) dans la chaîne de caractères, si le troisième paramètre count est spécifié, le remplacement ne peut pas dépasser count fois.
La syntaxe de replace() est :
str.replace(old, new[, count])
Le méthode replace() peut utiliser au plus3paramètres :
old -L'ancien sous-chaine que vous souhaitez remplacer
new -Le nouveau sous-chaine remplacera l'ancien sous-chaine
count(Optional)-The number of times you want to replace the old substring with the new substring
If count is not specified, the replace() method replaces all occurrences of the old substring with the new substring.
The replace() method returns a copy of the string where the old substring is replaced by the new substring. The original string remains unchanged.
If the old substring is not found, a copy of the original string is returned.
song = 'cold, cold heart' print(song.replace('cold', 'hurt')) song = 'Let it be, let it be, let it be, let it be' '''Only two occurrences of 'let' are replaced''' print(song.replace('let', "don't let", 2))
When running the program, the output is:
hurt, hurt heart Let it be, don't let it be, don't let it be, let it be
song = 'cold, cold heart' replaced_song = song.replace('o', 'e') # The original string has not changed print('The original string:', song) print('The replaced string:', replaced_song) song = 'let it be, let it be, let it be' # Replace up to 0 substrings at most # Returns a copy of the original string print(song.replace('let', 'so', 0))
When running the program, the output is:
The original string: cold, cold heart The replaced string: celd, celd heart let it be, let it be, let it be