Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python replacing all uppercase characters in a string with *

Is there a simple, straightforward way to turn this string:

"aBCd3Fg"

Into:

"a**d3*g"

In python 2.7?

like image 734
Monte Carlo Avatar asked Feb 03 '26 07:02

Monte Carlo


2 Answers

Not sure how fast you need this, but if you're looking for the fastest solution out there. The python string module's translate function is a slightly more roundabout, though generally more performant method:

import string

transtab = string.maketrans(string.uppercase, '*'*len(string.uppercase))
"aBCd3Fg".translate(transtab)

>>>'a**d3*g'

I'm always surprised about how many people don't know about this trick. One of the best guarded secrets in python IMO

like image 62
Slater Victoroff Avatar answered Feb 04 '26 20:02

Slater Victoroff


import re

print re.sub(r'[A-Z]', '*', "aBCd3Fg")
like image 32
crazyzubr Avatar answered Feb 04 '26 21:02

crazyzubr