Monte Carlo
Monte Carlo

Reputation: 457

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?

Upvotes: 3

Views: 3039

Answers (5)

adnanalhomssi
adnanalhomssi

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

kiasy
kiasy

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

smac89
smac89

Reputation: 43226

string = ''.join(['*' if x.isupper() else x for x in string])

Upvotes: 2

Slater Victoroff
Slater Victoroff

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

crazyzubr
crazyzubr

Reputation: 1082

import re

print re.sub(r'[A-Z]', '*', "aBCd3Fg")

Upvotes: 5

Related Questions