HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Change upper or lowercase vowels to [0,1,2,3,4] respectively and leave the rest the same

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
restrespectivelylowercasethesamevowelsleaveandupperchange

Problem

The objective was the following to be solved in Python:


Given a string, def a function that
returns another string with the vowels
(upper or lowercase) replaced by
0,1,2,3,4 respectively.




Example input:

"bB nN aei ou AEIOU"




Desired Output:

"bB nN 012 34 01234"





This is in fact quite trivial and can be solved in several ways, one way may be this:

def crypt(s):
    vow = ["a","e","i","o","u"]
    stringL = []

    for x in s:
        if x in vow or x.lower() in vow:
            stringL.append(str(vow.index(x.lower())))
        else:
            stringL.append(x)

    return "".join(stringL)


I was told this was over-complicated for such a simple task, that code like this would be difficult to debug etc.

Would you consider this approach a "bad" one, which way would you have gone instead, is it unclear?

Solution

Use string.maketrans().

from string import maketrans 

input = "aeiouAEIOU"
output = '0123401234'
trans = maketrans(input,output)
str = 'This is a Q&A site, not a discussiOn forUm, so please make sure you answer the question.'
print str.translate(trans)


Output:

Th2s 2s 0 Q&0 s2t1, n3t 0 d2sc4ss23n f3r4m, s3 pl10s1 m0k1 s4r1 y34 0nsw1r th1 q41st23n.

Code Snippets

from string import maketrans 

input = "aeiouAEIOU"
output = '0123401234'
trans = maketrans(input,output)
str = 'This is a Q&A site, not a discussiOn forUm, so please make sure you answer the question.'
print str.translate(trans)

Context

StackExchange Code Review Q#2164, answer score: 14

Revisions (0)

No revisions yet.