[Tutor] 'Name Genereator' Question
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Wed, 3 Jan 2001 20:22:14 -0800 (PST)
> The kicker (to me) is how to call "randint" for each character
> replacement target in "name". The easy way would be to "while" loop for
> "'.' in name", etc., or I could create a function to do the replacement
> and call it each time, but I thought there would be a more
> straightforward answer. (I'm probably missing something really, really
> simple here, right??)
Wait! Yes, on a second thought, you _can_ do a map() on a string --- but
you need to first convert it to a list. So you could write a
character-replacing function (let's call it replaceChar()), and then do
this:
###
def replaceString(str):
result = map(replaceChar, list(str))
return string.join(result, "")
###
where replaceChar() looks like:
###
def replaceChar(ch):
if ch == '.': return whrandom.choice(consonants)
elif ch == ',': return whrandom.choice(vowels)
else: return ch
###
And that would be a much nicer solution, I think. Hope this helps!