OneBite.Dev - Coding blog in a bite size

replace a substring within a string in python

Code snippet on how to replace a substring within a string in python

  test_string = "Hello, I'm a senior programmer"
  updated_string = test_string.replace("senior", "expert")
  print(updated_string)

This code replaces the substring “senior” with the substring “expert” in a sample string. In the first line, a string is assigned to the variable “test_string”. The built-in string method “.replace” is then called on the string with two arguments: the substring to search for replacement and the substring to be inserted for replacement. The line assigns the modified string to another variable called “updated_string”. Lastly, the new string is printed with the print command. The output is the original string but with “expert” instead of “senior” due to the successful replacement.

python