replace a substring in a string in python

There are different ways to replace a substring in a string, but one common method is to use the replace() method.

Here's an example:

main.py
my_string = "Hello world"
new_string = my_string.replace("world", "Python")
print(new_string)  # Output: Hello Python
118 chars
4 lines

In this example, the replace() method takes two arguments: the old substring to be replaced and the new substring to replace it with. The method returns a new string with the substitutions made.

Alternatively, you can use string slicing to replace a substring:

main.py
my_string = "Hello world"
new_string = my_string[:5] + "Python"
print(new_string)  # Output: Hello Python
106 chars
4 lines

In this example, the [:5] slice selects the characters up to the 5th position in the string, which includes the "Hello" part. By concatenating "Python" to this slice, we obtain a new string "Hello Python".

gistlibby LogSnag