Putting #'s and variables together in 1 variable

Jay Loden python at jayloden.com
Thu Aug 23 16:20:17 EDT 2007


Lamonte Harris wrote:
>   File "Desktop\python\newsystem\init.py", line 51, in random_n
>     random_name = a+b+c+d+e+ 'temp.txt'
> TypeError: unsupported operand type(s) for +: 'int' and 'str'
> 
> import random
> def random_name():
>     a = random.randint(0,9)
>     b = random.randint(0,9)
>     c = random.randint(0,9)
>     d = random.randint(0,9)
>     e = random.randint(0,9)
>     random_name = a+b+c+d+e+ 'temp.txt '
>     return random_name
> print random_name
> 
> How can i make it so that it adds the random numbers and the temp.txt to
> random_name variable w/out causing any error?

1) If you're just trying to create temporary files, you would be much better 
   off using the tempfile module. It's more secure and saves you the hassle 
   of doing it yourself: http://docs.python.org/lib/module-tempfile.html 

2) Since all you're doing is adding a bunch of numeric values to each other
   to build the string, why wouldn't you just create a random number between
   0 -> 99999 and use that?

3) If you really, really, really still want to do this, the best way I can 
   think of would be to use the string format operator: 

import random
def random_name():
    a = random.randint(0,9)
    b = random.randint(0,9)
    c = random.randint(0,9)
    d = random.randint(0,9)
    e = random.randint(0,9)
    random_name = '%s%s%s%s%stemp.txt' % (a,b,c,d,e)
    return random_name

OR, using suggestion 2 above:

import random
def random_name():
    num = random.randint(0,99999)
    random_name = '%stemp.txt' % (num)
    return random_name


-Jay



More information about the Python-list mailing list