0

Using Python, how can I get a randomized combination of letters?

I want to do something like this:

def ranStr():
    # some code
    return random_string

So, if I call ranStr(), I want to get out things like (random combination of random length of letters):

'aAFGresdFTg'
'EFRwdfWe'
'rgAijD'
5
  • 3
    Welcome to Stack Overflow! It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, stack traces, compiler errors - whatever is applicable). The more detail you provide, the more answers you are likely to receive. Commented Jan 27, 2013 at 23:26
  • 1
    And more likely your question won't be closed if you follow what Martijn just wrote to you :)
    – Lipis
    Commented Jan 27, 2013 at 23:29
  • 2
    It is now closed, but a edit of your post could save it still; make it a real question and you can ask for a reopen. Commented Jan 27, 2013 at 23:31
  • I think if you just copy some of the questions from here that would work.
    – Hot Licks
    Commented Jan 27, 2013 at 23:44
  • duplicate question: see stackoverflow.com/questions/3539945/…
    – mjv
    Commented Jan 28, 2013 at 3:52

1 Answer 1

2

This is one way of doing it.

import random
def generate_key():
    STR_KEY_GEN = 'ABCDEFGHIJKLMNOPQRSTUVWXYzabcdefghijklmnopqrstuvwxyz'
    return ''.join(random.choice(STR_KEY_GEN) for _ in xrange(70))

OR

import random, string
def generate_key():
    return ''.join(random.choice(string.ascii_letters) for _ in xrange(70))

Based on the suggestions.

3
  • Better: STR_KEY_GEN = string.letters Commented Jan 27, 2013 at 23:31
  • You don't need to type out the whole alphabet by the way. Have a look into the string module
    – phihag
    Commented Jan 27, 2013 at 23:31
  • random.choice(string.letters) gets a random letter, just keep doing it for a randint amount of times to get a random string. Commented Jan 27, 2013 at 23:38

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