[Tutor] Messy - Very Messy string manipulation.

Peter Otten __peter__ at web.de
Wed Oct 28 13:28:06 EDT 2015


Alex Kleider wrote:

> On 2015-10-28 09:37, Peter Otten wrote:
>> Vusa Moyo wrote:
>> 
>>> I've written a script to remove vowels from a string/sentence.
>>> 
>>> the while loop I'm using below is to take care of duplicate vowels
>>> found
>>> in a sentence, ie
>>> 
>>> anti_vowel('The cow moos louder than the frog')
>>> 
>>> It works, but obviously its messy and n00by. Any suggestions on how I
>>> can
>>> write this code better?
>> 
>> (I'm assuming Python3)
>> 
>>>>> 'The cow moos louder than the frog'.translate(str.maketrans("", "",
>> "aeiouAEIOU"))
>> 'Th cw ms ldr thn th frg'
>> 
> 
> I didn't know about the possibility of a third argument.  Thanks, Peter.
> 
> from the docs:
> """
> static str.maketrans(x[, y[, z]])
> 
>      This static method returns a translation table usable for
> str.translate().
> 
>      If there is only one argument, it must be a dictionary mapping
> Unicode ordinals (integers) or characters (strings of length 1) to
> Unicode ordinals, strings (of arbitrary lengths) or None. Character keys
> will then be converted to ordinals.
> 
>      If there are two arguments, they must be strings of equal length,
> and in the resulting dictionary, each character in x will be mapped to
> the character at the same position in y. If there is a third argument,
> it must be a string, whose characters will be mapped to None in the
> result.
> """
> 
> Although not explicitly stated, I assume that if there is a third
> argument, the first 2 will be ignored.

Don't guess, fire up the interactive interpreter ;)

>>> "abcdef".translate(str.maketrans("acf", "ACF", "bde"))
'ACF'

All argument have an effect. Now have a look at the dict created by 
maketrans:

>>> str.maketrans("acf", "ACF", "bde")
{97: 65, 98: None, 99: 67, 100: None, 101: None, 102: 70}

If the value is an int, str.translate() replaces chr(key) with chr(value), 
if the value is None chr(key) is removed. 

You can also replace one char with multiple chars, but for that you have to 
build the dict yourself:

>>> "ähnlich üblich löblich".translate(
... {ord(a): b for a, b in [
... ("ä", "ae"), ("ö", "oe"), ("ü", "ue")]})
'aehnlich ueblich loeblich'




More information about the Tutor mailing list