Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random strings in Python

Tags:

python

How do you create a random string in Python?

I needed it to be number then character repeat till you're done this is what I created

def random_id(length):     number = '0123456789'     alpha = 'abcdefghijklmnopqrstuvwxyz'     id = ''     for i in range(0,length,2):         id += random.choice(number)         id += random.choice(alpha)     return id 
like image 671
RHicke Avatar asked Jan 08 '10 19:01

RHicke


People also ask

How do you randomize a string?

To shuffle strings or tuples, use random. sample() , which creates a new object. random. sample() returns a list even when a string or tuple is specified to the first argument, so it is necessary to convert it to a string or tuple.

How do I get a list of strings from a random string in python?

In Python, you can randomly sample elements from a list with choice() , sample() , and choices() of the random module. These functions can also be applied to a string and tuple. choice() returns one random element, and sample() and choices() return a list of multiple random elements.

What does random () do in Python?

The random() method returns a random floating number between 0 and 1.


2 Answers

Generating strings from (for example) lowercase characters:

import random, string  def randomword(length):    letters = string.ascii_lowercase    return ''.join(random.choice(letters) for i in range(length)) 

Results:

>>> randomword(10) 'vxnxikmhdc' >>> randomword(10) 'ytqhdohksy' 
like image 76
sth Avatar answered Sep 20 '22 14:09

sth


Since this question is fairly, uh, random, this may work for you:

>>> import uuid >>> print uuid.uuid4() 58fe9784-f60a-42bc-aa94-eb8f1a7e5c17 
like image 39
Brandon Avatar answered Sep 20 '22 14:09

Brandon