Python Replace All Digits in String with Asterisks

Document 对象参考手册Python3 Examples

In Python, we can use the regular expression modulereto find all digits in a string and replace them with asterisks*. The following is a simple example code demonstrating how to implement this functionality.

Example

import re

def replace_numbers_with_stars(input_string):
    # Use regular expression to replace all digits with asterisks
    result = re.sub(r'd', '*', input_string)
    return result

# Example string
input_string = "Hello 123 World 456"
output_string = replace_numbers_with_stars(input_string)
print(output_string)

Code Analysis:

  1. import re: Import Python's regular expression modulere。
  2. re.sub(r'd', '*', input_string): Usere.subfunction to replace digits in the string.r'd'is a regular expression that matches any digit (0-9).'*'is the replacement character, indicating that all matched digits are replaced with asterisks.
  3. input_string = "Hello 123 World 456": Define a string containing digits.
  4. output_string = replace_numbers_with_stars(input_string): Call the functionreplace_numbers_with_starsto process the string.
  5. print(output_string): Output the processed string.

Output result:

Hello *** World ***

Document 对象参考手册Python3 Examples

Other Extensions