Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating random text strings of a given pattern

I need to generate random text strings of a particular format. Would like some ideas so that I can code it up in Python. The format is <8 digit number><15 character string>.

like image 621
Vijay Dev Avatar asked Dec 15 '08 06:12

Vijay Dev


People also ask

How do you generate a random text string in Java?

Using randomUUID() java. 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.

Can we generate random string?

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 .


1 Answers

#!/usr/bin/python  import random import string  digits = "".join( [random.choice(string.digits) for i in xrange(8)] ) chars = "".join( [random.choice(string.letters) for i in xrange(15)] ) print digits + chars 

EDIT: liked the idea of using random.choice better than randint() so I've updated the code to reflect that.

Note: this assumes lowercase and uppercase characters are desired. If lowercase only then change the second list comprehension to read:

chars = "".join( [random.choice(string.letters[:26]) for i in xrange(15)] ) 

Obviously for uppercase only you can just flip that around so the slice is [26:] instead of the other way around.

like image 110
Jay Avatar answered Oct 17 '22 01:10

Jay