1

I am trying to make a script that will generate a random string of text when i run it.

I have got far but im having a problem with formatting.

Here is the code im using

import random    
alphabet = 'abcdefghijklmnopqrstuvwxyz'

min = 5
max = 15

name = random.sample(alphabet,random.randint(min,max))

print name

And when ever i end up with this

['i', 'c', 'x', 'n', 'y', 'b', 'g', 'r', 'h', 'p', 'w', 'o']

I am trying to format so it is one line of string so for example

['i', 'c', 'x', 'n', 'y', 'b', 'g', 'r', 'h', 'p', 'w', 'o'] = icxnybgrhpwo
1
  • 2
    Note that the sample function always chooses a set of unique letters, so you'll run into a problem if max is greater than 26 (ValueError: sample larger than population). Commented Sep 23, 2011 at 5:22

3 Answers 3

12

join() it:

>>> name = ['i', 'c', 'x', 'n', 'y', 'b', 'g', 'r', 'h', 'p', 'w', 'o']
>>> ''.join(name)
'icxnybgrhpwo'
1
  • Awesome it worked i put the variable in there i came up with ''.join(name)
    – user705260
    Commented Sep 23, 2011 at 5:13
1
import string
import random

def create_random(length=8):
    """ Create a random string of {length} length """
    chars = string.letters + string.digits
    return ''.join(random.Random().sample(chars, length))
0

An easy way to print an alphabet :

>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'

(source)

Not the answer you're looking for? Browse other questions tagged or ask your own question.