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?

1
  • 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. Commented Oct 28, 2018 at 19:57

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

and call it with random_string(random.randint(1, max_length))
In Python 3 you need to use string.ascii_lowercase
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()

4 Comments

@HughChalmersAdvanced I have updated the answer.
This should have been an edit to Harrison's answer and not a separate answer, since it was basically the same as his.
@XanderLuciano OP doesn't have to pass length to my function.
Keeping aside the fact that this answer is almost identical to Harrison's, using a global variable makes it uglier. The other answer is much much cleaner in this regard. If you don't want to pass a value, give the parameter a default value.
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)

1 Comment

This is not uniformly distributed. Smaller strings have higher chances.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.