Python String replace method with Example – Python Tutorial

1 year ago Lalit Bhagtani 0

In this tutorial, we will learn about python string replace method.
Python String Replace

replace method :

This method returns a copy of the string in which all the occurrences of old string ( passed as a first argument ) had been replaced by the new string ( passed as a second argument ). If optional third argument count  is passed, then replace method limits the replacement operation ( new string replacing old string ) to the maximum of number count.

Syntax : < String Object >.join( old_String, new_String[, count] ) :  < String Object >

Example:

[datacamp_exercise lang=”python” height=”350″ min-height=”300″ max-height=”500″]
[datacamp_pre_exercise_code]

[/datacamp_pre_exercise_code]
[datacamp_sample_code]
# create one string and assign it to variable s
s = ‘I am here and only here and only here’

# call replace() method on string s by passing ‘here’ (old string) and ‘there’ (new string) as an argument
output = s.replace(‘here’,’there’)

# print the value of variable output
print(output)

# call replace() method on string s by passing ‘here’ (old string), ‘there’ (new string) and 2 as an argument
output = s.replace(‘here’,’there’,2)

# print the value of variable output
print(output)
[/datacamp_sample_code]
[datacamp_solution]

[/datacamp_solution]
[/datacamp_exercise]

References :-

  1. replace() method Docs

That’s all for Python String replace method. If you liked it, please share your thoughts in comments section and share it with others too.

Previous