How do I generate a random alphanumeric string in Python?
Question:
I have been migrating javascript code to python and I am stuck trying to get a python version of
Math.random().toString(36)
I’m not sure how to do this since Math.random()
returns a float, in python I have not been able to figure out how to convert a float to base36. From what I understand it’s only int
but then how does javascript do it?
for getting a random float in python I just use the following:
import random
random.uniform(0, 1)
and for encoding I used the wiki example:
#from wiki
def base36encode(integer: int) -> str:
...
-EDIT:
original js code:
function randomString(length) {
return Array(length + 1).join((Math.random().toString(36) + '00000000000000000').slice(2, 18)).slice(0, length);
}
Answers:
Going from comments. In JS using base36 is done to generate random alphanumeric characters. That is 26 from the alphabet + 10 digits.
In python you can generate a random alphanumeric string of a given length like this:
import random, string
def random_string(length):
return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length))
import random
import string
Define the length of the string
length = 10
Define the pool of characters to choose from
pool = string.ascii_letters + string.digits
Generate the random string
random_string = ''.join(random.choice(pool) for i in range(length))
print(random_string)
I have been migrating javascript code to python and I am stuck trying to get a python version of
Math.random().toString(36)
I’m not sure how to do this since Math.random()
returns a float, in python I have not been able to figure out how to convert a float to base36. From what I understand it’s only int
but then how does javascript do it?
for getting a random float in python I just use the following:
import random
random.uniform(0, 1)
and for encoding I used the wiki example:
#from wiki
def base36encode(integer: int) -> str:
...
-EDIT:
original js code:
function randomString(length) {
return Array(length + 1).join((Math.random().toString(36) + '00000000000000000').slice(2, 18)).slice(0, length);
}
Going from comments. In JS using base36 is done to generate random alphanumeric characters. That is 26 from the alphabet + 10 digits.
In python you can generate a random alphanumeric string of a given length like this:
import random, string
def random_string(length):
return ''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length))
import random
import string
Define the length of the string
length = 10
Define the pool of characters to choose from
pool = string.ascii_letters + string.digits
Generate the random string
random_string = ''.join(random.choice(pool) for i in range(length))
print(random_string)