Python Replace All Digits in a String with Asterisks
In Python, we can use the regular expression module re to find all digits in a string and replace them with asterisks *. The following simple example code shows how to do this.
Example
import
re
def
replace_numbers_with_stars
(
input_string
)
:
Use a 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
)
(
output_string
)
Code analysis:
import re: Import Python's regular expression modulere。re.sub(r'd', '*', input_string): When usingre.subfunction to replace the digits in the string.r'd'is a regular expression that matches any digit (0-9).'*'is the replacement character, meaning that all matched digits are replaced with asterisks.input_string = "Hello 123 World 456": define a string containing numbers.output_string = replace_numbers_with_stars(input_string): Call the functionreplace_numbers_with_starsto process the string.print(output_string): Print the processed string.
Output result:
Hello *** World ***
Python3 Examples