Python Replace All Digits in String with Asterisks
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)
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:
import re: Import Python's regular expression modulere。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.input_string = "Hello 123 World 456": Define a string containing digits.output_string = replace_numbers_with_stars(input_string): Call the functionreplace_numbers_with_starsto process the string.print(output_string): Output the processed string.
Output result:
Hello *** World ***Other Extensions
Python3 Examples