[Tutor] 'Name Genereator' Question

Daniel Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 3 Jan 2001 20:15:17 -0800 (PST)

On Wed, 3 Jan 2001, Curtis Larsen wrote:

> I'm writing a quickie little script that generates names, to better
> understand string manipulation.  What I'd like to have is something like
> "map" that can be used against a number of occurrences of a character in
> a string and replace it -- without using a lot of loops.

Here are small things that might improve your program:

The whrandom module has a function called "choice()" which lets you grab
at a random element out of a list.  So, instead of:


you could use:


which is a bit nicer to read.  whrandom.choice() works on strings as well
as lists, so its a nice function.

> 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??)

Creating a function that does the replacement would be nice.  Here's

def replaceStuff(str):
    # Let's first make str a mutable list.
    # The reason for this is because we can modify a
    # list "in-place".
    templist = list(str)

    # Time for the replacement stuff
    for i in range(len(templist)):
        if templist[i] == '.":
            templist[i] = whrandom.choice(vowels)
    # skipping consonant stuff

    # finally, bring the list back as a string:
    return string.join(templist, "")

So the loop goes through each character on your list, but you only do
something if that character is a '.' or a ','.  I haven't tested the code
above yet, but I hope that it makes sense.