Reputation: 457
Is there a simple, straightforward way to turn this string:
"aBCd3Fg"
Into:
"a**d3*g"
In python 2.7?
Upvotes: 3
Views: 3039
Reputation: 129
A simple solution :
input = "aBCd3Fg"
output = "".join(['*' if 'A' <= char <= 'Z' else char for char in input ])
#Long version
input = "aBCd3Fg"
output = ''
for char in input:
output = output + '*' if ord('A') <= ord(char) <= ord('Z') else output + char
print output
Upvotes: 1
Reputation: 304
You can also do:
for x in myString:
if (x == 'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'"
x = '*'
That's a short piece of code that will do the work.
Upvotes: -3
Reputation: 21934
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
Upvotes: 6