Python-Ref > String manipulation > String basics > Replacing parts of a string
 
 

<-^^
Klíčová slova
Moduly
Knihovní funkce

Replacing parts of a string

Strings contain a method called replace which returns a copy of the string with all pieces matching the first argument being replaced by the second argument.
Expand/Shrink
  1   x = "dog,cat,pig,hippo,chicken"
  2   y = x.replace(",",";")
  3   print y
  4   
  5   print y.replace(";"," -- ")
  6   print x.replace(",",", ")
stdout:
dog;cat;pig;hippo;chicken
dog -- cat -- pig -- hippo -- chicken
dog, cat, pig, hippo, chicken
Doba běhu: 14.0 ms
Because string replacement does not require the replaced and new strings to be the same length, it can be used for many thing, including removal of unwanted characters.
Expand/Shrink
  1   text = "This is * mangled text & with some %% strange characters ^^"
  2   print text
  3   
  4   text = text.replace( "*", "")
  5   print text
  6   
  7   text = text.replace("%","").replace("&","").replace("^","")
  8   print text
stdout:
This is * mangled text & with some %% strange characters ^^
This is  mangled text & with some %% strange characters ^^
This is  mangled text  with some  strange characters 
Doba běhu: 13.6 ms
The replace method has one optional argument count which can limit the number of replacements made.
Expand/Shrink
  1   x = "dog,cat,pig,hippo,chicken"
  2   print x.replace(",", ";")
  3   print x.replace(",", ";", 1)
stdout:
dog;cat;pig;hippo;chicken
dog;cat,pig,hippo,chicken
Doba běhu: 13.6 ms
Note: it is possible to perform more powerful (but slightly slower) replacements by using regular expressions. For more information see Replacement.