Python String – Replace using regular expression

Python String – Replace using regular expression

In Python, you can use the re module to perform string replacement using regular expressions.

In re module there is sub() function which takes a patterns and then replaces all the matching substrings in the original string, with a new replacement string.

modified_string = re.sub(pattern, replacement, input_string)


  • input_string: The original string.
  • pattern: The regular expression pattern to match.
  • replacement: The string to replace the matched substrings.

re.sub() replaces all the substrings in the input_string that match the specified pattern with the replacement string.

Adjust the original_string, pattern_to_replace, and replacement_string variables according to your specific use case.

Now, let us take an example, where we replace all the words in the given string with 'apple' replacement string. The pattern we use for a word is one or more adjacent uppercase or lowercase alphabets.

Python Program

import re

# Given
original_string = "Hello, World! 123"
pattern = r'[A-Za-z]+'
replacement_string = "apple"

# Replace all the pattern matchings
result_string = re.sub(pattern, replacement_string, original_string)

Run Code Copy


apple, apple! 123

Related Tutorials

Code copied to clipboard successfully 👍