Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate in flight string from [A-z]

Tags:

python

random

I want to know what is a simplest way to write method which generates me number from 1 to 50, and then depends of generated number returns me string like:

Abcdef if generated number is 6
Abcdefghi if generated number is 9.

I'm using python 3.2

like image 931
user278618 Avatar asked May 30 '11 09:05

user278618


People also ask

How do you generate random strings?

Using the random index number, we have generated the random character from the string alphabet. We then used the StringBuilder class to append all the characters together. If we want to change the random string into lower case, we can use the toLowerCase() method of the String .

How do you generate a random string of letters in python?

random. choice() is used to generate strings in which characters may repeat, while random. sample() is used for non-repeating characters.

How do you generate a random string of characters in Java?

Using randomUUID() util. UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.


1 Answers

There's a few approaches, the simplest:

>>> import string
>>> import random
>>> string.ascii_letters[:random.randint(1, 50)].title()
'Abcdefghijklmnopq'
>>> string.ascii_letters[:random.randint(1, 50)].title()
'Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopq'
>>> string.ascii_letters[:random.randint(1, 50)].title()
'Abcdefghijklmnopqrs'    

Or you can have a go with itertools:

>>> import string
>>> import random
>>> from itertools import islice, cycle
>>> def randstr():
...     return ''.join(islice(cycle(string.ascii_lowercase),
...                           random.randint(1, 50))).title()
...
>>> randstr()
'Abcdefghijklmnopq'
>>> randstr()
'Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopq'
>>> randstr()
'Abcdefghijklmnopqrs'    
like image 79
bradley.ayers Avatar answered Sep 21 '22 23:09

bradley.ayers