Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Replace All Digits in a String with Asterisks

Python Replace All Digits in a String with Asterisks

Document Object Reference Manual Python3 Examples

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

)

print

(

output_string

)

Code analysis:

  1. import re: Import Python's regular expression module re。
  2. re.sub(r'd', '*', input_string): When using re.sub function 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.
  3. input_string = "Hello 123 World 456": define a string containing numbers.
  4. output_string = replace_numbers_with_stars(input_string): Call the function replace_numbers_with_stars to process the string.
  5. print(output_string): Print the processed string.

Output result:

Hello *** World ***

Document Object Reference Manual Python3 Examples