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
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.
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.
The random() method returns a random floating number between 0 and 1.
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'
Since this question is fairly, uh, random, this may work for you:
>>> import uuid >>> print uuid.uuid4() 58fe9784-f60a-42bc-aa94-eb8f1a7e5c17
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With