I am coming from a Ruby background and I am learning Python. This is a method I've created to generate a URL safe unique key:
import random;
def generate_unique_key():
array = []
for letter in range(97,123):
array.append(chr(letter))
for letter in range(65,91):
array.append(chr(letter))
for number in range(0,10):
array.append(number)
for char in ["-", ".", "_", "~"]:
array.append(char)
random_values = random.sample(array, 15)
random_values = map(lambda x: str(x), random_values)
return "".join(random_values)
print(generate_unique_key())
Coming from a Ruby background I was certainly puzzled first at not being able call join
directly on my list, but having to call it from a string instance.
Also in Ruby I would have written something similar to random.sample(array, 15).join("")
directly without having to convert them all to string, but this I believe this is how join()
works.
While this works, how can this function be more Pythonic?