How can I replace a substring in a string in Python?
Davide S
davide s profile pic

In Python, you can replace a substring within a string using thereplace() method or by utilizing string manipulation techniques. Here's a detailed explanation of both approaches: Using the replace() method: Thereplace() method is called on a string and replaces all occurrences of a specified substring with a new substring.

1
2
3
4
5
6

my_string = "Hello, World!"

new_string = my_string.replace("World", "Universe")

print(new_string)  # Output: "Hello, Universe!"

In this example,my_string.replace("World", "Universe") replaces all occurrences of the substring "World" with "Universe" in the stringmy_string. The resulting modified string is assigned to the variablenew_string. Using string manipulation: If you don't want to use thereplace() method, you can utilize string manipulation techniques such as slicing and concatenation to achieve the substring replacement.

1
2
3
4
5
6
7
8
9
10
11
12
13

my_string = "Hello, World!"

substring = "World"
replacement = "Universe"

index = my_string.find(substring)

if index != -1:
    new_string = my_string[:index] + replacement + my_string[index + len(substring):]
    print(new_string)  # Output: "Hello, Universe!"
else:
    print("Substring not found.")

In this example, thefind() method is used to locate the index of the first occurrence of the substring "World" withinmy_string. If the substring is found (index != -1), the new string is constructed by concatenating the portions of the original string before and after the substring, with the replacement substring in between. If the substring is not found, a message is printed indicating that the substring was not found. Both approaches allow you to replace a substring within a string in Python. Thereplace() method provides a more straightforward and concise solution, while string manipulation techniques give you more control and flexibility. Choose the method that best suits your needs based on the specific requirements of your program.