

Regular expressions are hard to understand and need to be used carefully to match the characters that are to be replaced correctly. Generally, we need to use regular expressions to find characters in a string to replace them. New_string = input_string.replace('a', "A",3)Īn owl sat on the back of an elephant and started to tease him.Īn owl sAt on the bAck of An elephant and started to tease him. input_string = "An owl sat on the back of an elephant and started to tease him." After specifying the number of occurrences of the characters to be replaced, n occurrences of characters from the start of the string will be replaced.įor example, we can replace the first 3 occurrences of character ‘a’ in the given text with ‘A’ as follows. To replace the first n occurrences of characters of a string with another character, we can specify the optional input argument in the replace() method. Replace first n occurrence of a character in a string In this example, you can see that we have replaced “is” with “IS” in the output string. Here, you can read python tutorials for free. New_string = input_string.replace('is', "IS") Here, you can read python tutorials for free." We just have to pass the old characters and new characters to the replace() method as follows. The syntax for replacing the group of consecutive characters remains unchanged. We can also replace a group of consecutive characters with a new group of characters instead of replacing a single character. Here, we have replaced all occurrences of the character ‘i’ with the character ‘I’ using the replace() method. Here, you can read python tutorIals for free. New_string = input_string.replace('i', "I")

You can observe this in the following example. To replace all the occurrences of a character with a new character, we simply have to pass the old character and the new character as input to the replace() method when it is invoked on the string. Replace all occurrences of a character in a string Let us now discuss how we can replace characters in a string using various use cases. The input n is the optional argument specifying the number of occurrences of old_character that has to be replaced with the new_character. Here, old_character is the character that will be replaced with the new_character.
