string random generator (Sorry if too stupid, but i am a beginner)

Skip Montanaro skip at pobox.com
Fri Jul 20 14:21:33 EDT 2001


    Gustavo> I am in need for a function that return a string of len x
    Gustavo> random generated, like

    Gustavo> strrnd(5)
    Gustavo> 'Df%d^'

    Gustavo> strrnd(2)
    Gustavo> '&@'

    Gustavo> I have the following code: The problem is that i don't known
    Gustavo> how to map a int to a char. 

You would use the chr() builtin function.

Perhaps this version will work for you:

    import random
    chars = "".join([chr(x) for x in range(ord(' ')+1,128)])

    def strrnd(n, charset=chars):
        return "".join([random.choice(charset) for i in range(n)])

    def _test():
        print strrnd(5)
        print strrnd(7)
        print strrnd(0)
        print strrnd(2)

    if __name__ == "__main__":
        _test()

This uses list comprehensions, so Python 2.x is required to run it with
changes. 

-- 
Skip Montanaro (skip at pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/




More information about the Python-list mailing list