Python String replace() Method

16-01-23 Ahmed Obaid 1695 0

​The replace() function returns a new copy of the string in which all occurrences of the substring are replaced by another substring. It can also specify how often substrings should be replaced by another substring.

Example of using the replace() function: This function can be used to replace multiple similar misspellings in any document at once.


How to formulate it like this:


string. replace(old, new, count)

old : The old substring we want to replace.

new : The new substring that we want to replace the old substring with.

count : ( optional ) Specifies the number of times we want to replace the old substring with the new substring. .

Return value: Returns a new string in which all occurrences of the old substring are replaced by the new substring.


In the following example we will replace one character from a given string. Note that the replace() function is case sensitive so the letter A in Ahmed remains unchanged.

Example:


string = "Ahmed obaid"
# replace all instances of 'a' (old) with 'e' (new
new_string = string.replace("a", "e" )
print(string)
print(new_string)

 The output will be:


Ahmed obaid
Ahmed obeid

 In the following example, we will replace the word python in the old string with the word django in the new string

 Example:


string = " learn python with ahmed obaid"
# replace all instances of 'python' (old) with 'django' (new)
new_string = string.replace("python", "django" )
print(string)
print(new_string)

 The output will be:


learn python with ahmed obaid
learn django with ahmed obaid

 In the following example we will replace a certain number of characters. i.e. "x" with "a" with number = 2 .


string = " learn python with ahmed obaid"
# replace all instances of 'a' (old) with 'x' (new)
new_string = string.replace("a", "x" , 2)
print(string)
print(new_string)

 The output will be:


learn python with ahmed obaid
lexrn python with xhmed obaid

 Notice in the previous example that the letter a in the word obaid has not changed. Because we have limited the number of replacements allowed. It is 2 times

 External sources:

 Built-in functions - official Python documentation

 If you have any questions or concerns, leave them in the comments



Tags


Python Python String string methods python python string replace method

Share page