Changing a string in Python – the replace method

by Alex
Changing a string in Python - the replace method

Strings are an important data type in almost any programming language. It is used to create, modify, and save textual information, and it is also used in some number-related tasks. Python gives the programmer many tools for working with strings, including the replace() method.

What the method does

The word replace has a literal translation of “replace”, so the name of the method accurately describes its purpose. With replace, you can replace part or all of a string with another string. The syntax of the method looks like this:

str.replace(old_str, new_str[, count])

The arguments passed to the method are:

  • old_str – part of the original string to be replaced.
  • new_str – the string to which the original string(old_str) is replaced.
  • count – specifies the number of occurrences of the substring to be replaced.
Here count is an optional parameter. If it is not specified, all substring occurrences will be replaced by new ones.

The original string (data type string) is used as str. Thus, the method replace allows to flexibly change only the necessary parts of the string str, which is shown in the following examples:

my_str = "one dog, one cat, one rabbit"

#Replace all occurrences of "one" in a string
a = my_str.replace("one", "two")
print(a) # Prints two dog, two cat, two rabbit

#For the first "one" in the string
b = my_str.replace("one", "two", 1)
print(b) # Prints two dog, one cat, one rabbit

#Substitute the first two occurrences of "one" in the string
c = my_str.replace("one", "two", 2)
print(c) # Prints two dog, two cat, one rabbit
It’s important to remember that strings are immutable sequences. So the replace method doesn’t replace individual characters in the target string; instead, it creates a copy of it with the changes you want. This is an important feature of Python that every programmer should know.

It is not obvious, you can use the replace method to replace several values at once, for example all elements of a list:

str_list = ["cat", "dog", "cat dog", "cat cat"]

# we write the elements of the original list changed in the new list
# by using replace
result_list = [elem.replace("cat", "cat", 1) for elem in str_list]
print(result_list) # will print ['cat', 'dog', 'cat dog', 'cat cat']

Using replace to replace multiple values

With dictionary

The previous example allows you to replace several elements, but they all have the same meaning ‘cat’. If you want to replace several different values, for example ‘cat’ with ‘cat’ and ‘cat’ with ‘dog’, you need to implement a slightly more complicated program using dictionaries:

# Function for replacing multiple values
def multiple_replace(target_str, replace_values):
    # get the replaceable: substituted from the dictionary in the loop
    for i, j in replace_values.items():
        # change all target_str to substitutable
        target_str = target_str.replace(i, j)
    return target_str

# create a dictionary with values and a string to change
replace_values = {"cat": "cat", "cat": "dog"}
my_str = "I have a cat and a cat"

# change and print the string
my_str = multiple_replace(my_str, replace_values)
print(my_str)

Here replace is used in a function whose arguments are a source string and a dictionary with values to replace. This variant of the program has a significant disadvantage, the programmer can’t be sure what result he/she will get. The point is that dictionaries are sequences without a certain order, so the example program can lead to two different results, depending on how the interpreter arranges the dictionary elements:

  • I have a dog and a dog
  • I have a cat and a dog
In Python version 3.6 and later, the order in which the keys are enumerated will be the same as the order in which they are created. In earlier versions of Python, the order may be different.

To solve this problem, you can replace the usual dictionary with an OrderedDict dictionary, which you need to import with the following command:

from collections import OrderedDict

In addition to the import you need to change literally one line in the program:

replace_values = {"cat": "cat", "cat": "dog"}

Change it to:

replace_values = OrderedDict([("cat", "cat"), ("cat", "dog")])

In this case, the result will be “I have a dog and a dog”. If you swap the elements of the ordered dictionary during initialization as follows: OrderedDict([("cat", "dog"), ("cat", "cat")]), then the result will be “I have a cat and a dog”.

A variant with lists

We can implement multivalue substitution in another way, using lists:

my_str = "I have a cat and a cat"
# in the loop, pass the list (to be replaced and substituted) to the replace method
for x, y in ("cat", "cat"), ("cat", "dog")
    my_str = my_str.replace(x, y)
print(my_str) # Prints "I have a dog and a dog."

In this example, the for loop does two iterations:

  1. Substitutes values from the first list into the replace method: replace(“cat”, “cat”), resulting in the string “I have a cat and a cat”.
  2. Substitutes values from the second list into the replace method: replace(“cat”, “dog”), resulting in the string “I have a dog and a dog”.

Other Python types and the replace method

The replace method is not just for strings, the programmer can use it to change sequences of bytes, time and date. The syntax for byte sequences is the same as for strings, but for dates and times the replace method arguments must contain the identifier of the target to be changed, for example

from datetime import date

t_date = date(2020, 4, 23)
t_date = t_date.replace(day = 11)
print(t_date) # Outputs 2020-04-11

For time, the replace method is applied similarly.

Related Posts

LEAVE A COMMENT