2

I wanted to know how to print a random string in Python. I want this to be a random string like "ayhbygb", and be a random amount of letters long. So like, one time it could print "a", the next time it could print "aiubfiub", or "aiuhiu", etc.

Could someone tell me how this would be done?

ayhan
  • 70,170
  • 20
  • 182
  • 203
  • This is not a duplicate from the question it's marked as a duplicate of. Hugh Chalmers is asking for variable length and the answered question is for fixed size strings. – Rafael Almeida Oct 28 '18 at 19:57

3 Answers3

6

You can do this, however, you'll have to specify the maximum length that the string can be. You could always generate a random number for max_length as well.

import random, string

def random_string(length):
   return ''.join(random.choice(string.lowercase) for i in range(length))

max_length = 5
print(random_string(rando‌​m.randint(1, max_length)))

Here are 5 test cases:

print(random_string(random.randint(1, max_length)))
print(random_string(random.randint(1, max_length)))
print(random_string(random.randint(1, max_length)))
print(random_string(random.randint(1, max_length)))
print(random_string(random.randint(1, max_length)))

And their output is:

wl
crhxl
uvl
ty
iuydl

You can of course change the maximum length for the string by changing the max_length variable to whatever you'd like.

Harrison
  • 5,095
  • 7
  • 40
  • 60
0

Variable string, variable length:

>>>import random, string    
>>>max_rand_str_length = 10
>>> def genCustomString():
...    return ''.join(random.choice(string.lowercase) for _ in range(random.choice(range(1, max_rand_str_length))))
... 
>>> genCustomString()
'v'
>>> genCustomString()
'mkmylzc'
>>> genCustomString()
'azp'
>>> genCustomString()
Nehal J Wani
  • 16,071
  • 3
  • 64
  • 89
0

Might not be the most elegant, but this should do the trick. And if you want just lower case you can replace "string.ascii_letters" with string.ascii_lowercase.

import random
import string

MIN_NUM_CHAR = 5
MAX_NUM_CHAR = 25
num_char = random.randint(MIN_NUM_CHAR, MAX_NUM_CHAR)

rand_string = ""
for i in range(num_char):
    rand_string += random.choice(string.ascii_letters)

print(rand_string)
tuzzer
  • 1,119
  • 3
  • 12
  • 20