Mujtaba
Mujtaba

Reputation: 260

Generate random string with specific pattern

I'm trying to generate a wordlist using random module. The pattern I want is like this:

D7FE-PWO3-ODKE

I can generate the strings but I'm not able to figure out how can I get that hyphen (-) between them.

import random
import string

wordlist = string.ascii_uppercase + string.digits

def random_string(len):

    for i in range(10):
        result = ''.join(random.choice(wordlist) for _ in range(len))
        print(result)

random_string(12)

I have tried this approach but this gives whitespaces after each (-).

def random_string():
    
    for i in range(10):
        str1 = ''.join(random.choice(wordlist) for _ in range(4)) + '-'.strip()
        str2 = ''.join(random.choice(wordlist) for _ in range(4)) + '-'.strip()
        str3 = ''.join(random.choice(wordlist) for _ in range(4))
        print(str1, str2, str3)

random_string()

Upvotes: 0

Views: 921

Answers (2)

Richard
Richard

Reputation: 36

I would suggest this more flexible and simplier solution which adds only one line of code and still keep readability.

After generation of string, you simply cut the string by every 4 chars and glue them with hyphens.

import random
import string


wordlist = string.ascii_uppercase + string.digits


def random_string(str_len, count=10):
    for i in range(count):
        result = ''.join(random.choice(wordlist) for _ in range(str_len))
        # Next line adds the hyphens every 4 characters.
        result = '-'.join(result[i:i + 4] for i in range(0, len(result), 4))
        print(result)


random_string(12)

You can also provide another parameters e.g. group=4 etc. to create even more flexible function. :)

Edit: This is not list comprehension version of the hyphen concatenation for cycle:

results = []
for i in range(0, len(result), 4):
    results.append(result[i:i + 4])
print('-'.join(results))

Upvotes: 1

alec_djinn
alec_djinn

Reputation: 10789

You can simply use f-string-formatting

def random_string():
    for i in range(10):
        str1 = ''.join(random.choice(wordlist) for _ in range(4))
        str2 = ''.join(random.choice(wordlist) for _ in range(4))
        str3 = ''.join(random.choice(wordlist) for _ in range(4))
        
        final = f'{str1}-{str2}-{str3}'
        print(final)

Upvotes: 1

Related Questions