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 6Abcdefghi
if generated number is 9.
I'm using python 3.2
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 .
random. choice() is used to generate strings in which characters may repeat, while random. sample() is used for non-repeating characters.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With