To “replace 0 in a string with 91” means to substitute every occurrence of the character ‘0’ with the characters ’91’ in the given string.
For example, if you have a string:
“Hello 0 Chennai 0”
After the replacement, it would become:
“Hello 91 Chennai 91”
So, every ‘0’ in the original string is replaced by ’91’. This is a straight forward text substitution where you look for a specific substring (‘0′) and replace it with another substring (’91’)
Steps to achieve the transformation
- Start from the beginning of the string and examine each character.
- Whenever you encounter ‘0’, replace it with ’91’.
- Continue this until you have checked and replaced all instances of ‘0’ in the string.
Identify the target character:
You need to locate each occurrence of the character ‘0’ in the string.
Perform the replacement:
This process needs to be applied iteratively to the entire string because there might be multiple instances of ‘0’ that need to be replaced.
Iterate through the string:
This process needs to be applied iteratively to the entire string because there might be multiple instances of ‘0’ that need to be replaced.
So, the replace 0 in a string with 91 transform every instance of the substring ‘0’ to ’91’ throughout the entire string.
String involves iterating through each character of the string and performing.
- Initialize an empty result string
- Iterate through each character
- Check for ‘0’
- Construct the modified string
def replace_0_with_91(input_string): replace '0' with '91' output_string = input_string.replace('0','91') return output_string input_str="Hello 0 Chennai 0" output_str = replace_0_with_91(input_str) print("Input string:",input_str) print("Output string:",output_str)
OUTPUT:
Input string: Hello 0 Chennai 0
Output string: Hello 91 Chennai 91
This program is simpler and more concise compared to the previous one using manual iteration and appending. It leverage python efficient string manipulation capabilities provided by the replace method to achieve the desired replacement.