81 of 151 menu

The replace method

The replace method searches and replaces a string. In the first parameter of the method, we specify the substring we want to replace. In the second parameter, we specify what we want to replace it with. In the third optional parameter, you can specify the number of times the substring will be replaced.

Syntax

string.replace(what we change, what we change, [number of replacements])

Example

Let's replace all the characters 'a' with !:

txt = 'abacdea' print(txt.replace('a', '!'))

Result of code execution:

'!b!cde!'

Example

Now let's set the number of replacements:

txt = 'abacdea' print(txt.replace('a', '!', 2))

Result of code execution:

'!b!cdea'

See also

  • method index,
    which finds the index of a matching substring in a string
  • method format,
    which substitutes data using string formatting
  • method count,
    which returns the number of occurrences of a substring in a string
  • method endswith,
    which checks for a substring from the end of a string
  • method find,
    which returns the index of the first match of a substring in a string
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline