Different methods to change the string content

Let’s discusses about the different ways to replace the substring with another text content

I don’t want to waste your time by discussing about What is string, Unicode characters of string. One important to note here is that all the string methods always return new values and do not change or manipulate the original string.

Replace multiple values with different substrings.

text = "Lung cancer or bronchogenic carcinoma refers to tumor originating in the lung parenchyma or within bronchi."char_to_replace = {'Lung': 'kidney', 'tumor': 'tumors', 'bronchogenic carcinoma': ''}def string_replace_fuc(text, char_to_replace):
"""Iterate over all key-value pairs in dictionary"""
for key, value in char_to_replace.items():
# Replace key character with value character in string
text = text.replace(key, value)
return text
Function output

In the above code we are saving the text content “text” variable and again we are changing content in text and saving it as a text, because as we discussed earlear we can’t change original content in the string, we need save the changes content as new variable.

Replace substring in the string

We can replace substring with replace method.

text = "Lung cancer or bronchogenic carcinoma refers to tumor originating in the lung parenchyma or within bronchi."new_text = text.replace("Lung", " kidney")
print(new_text)

Replace multiple values with same substrings.

text = "Lung cancer or bronchogenic carcinoma refers to tumor originating in the lung parenchyma or within bronchi."repl_char = 'Kidney'repl_list = ['Lung', 'bronchogenic', 'parenchyma']for ele in repl_list:
text = text.replace(ele, repl_char, 1)
# printing result
print("String after replacement : ", text )

And output will be like below,

Thanks for reading…