Random string generation

I'm interested in how you can generate a string like sa32Asf7w1 using the random library in python. The first 4 characters are a random set of letters and numbers, from 6 to 10 the same. 5 character - random capital letter.

Author: Danis, 2020-10-29

4 answers

As an option-make a dictionary of letters and numbers and choose from there, and choose the 5 character from a separate dictionary (where only large letters) or from the same dictionary, only with borders corresponding to large letters

Final version:

import random
import string

text = [random.choice(string.ascii_lowercase + string.digits if i != 5 else string.ascii_uppercase) for i in range(10)]

print(''.join(text))

Variants:

import random

letters = ['A', 'B', 'C', 'a', 'b', 'c', '1', '2', '3']

text = [letters[random.randint(0, len(letters))] for _ in range(10)]
text[5] = letters[random.randint(0, 3)]

print(''.join(text))

P.S.

Yes, through choice the code is more compact

import random

text = [random.choice('abc123') for _ in range(10)]
text[5] = random.choice('ABC')

print(''.join(text))

Or even so:

text = [random.choice('abc123') if i != 5 else random.choice('ABC') for i in range(10)]

print(''.join(text))

Or so (still save a little on the length):):

text = [random.choice('abc123' if i != 5 else 'ABC') for i in range(10)]
 7
Author: Zhihar, 2020-10-29 18:21:48
from random import choice
import string
all = string.ascii_lowercase + string.digits
five = string.ascii_uppercase
print(''.join(choice(all) for _ in range(5)) + choice(five) + ''.join(choice(all) for _ in range(6, 11)))
 5
Author: Victor VosMottor, 2020-10-29 18:14:11

It is strange that so far no one has given the Pythonic solution itself:

from string import ascii_lowercase, ascii_uppercase, digits
from random import choice, choices

letters_and_digits = ascii_lowercase + digits

res = ''.join(choices(letters_and_digits, k=4))  # Сначала выбираем 4 любых буквы/цифры
res += choice(ascii_uppercase)  # Одну uppercase букву
res += ''.join(choices(letters_and_digits, k=5))  # Ещё 5 букв или цифр

print(res)
 5
Author: Михаил Муругов, 2020-10-29 18:47:17

I can suggest something like this:

from random import randint

def getRandStr(lenght):
    return "".join(chr(randint(33, 125)) for _ in range(lenght))


res = getRandStr(4) + chr(randint(65, 90)) + getRandStr(5)
print(res)

In principle, everything is simple:

  • The getRandStr(lenght) function generates random characters (based on their ascii codes, range from 33 before 125 these are Latin letters, numbers, and punctuation marks. If you are not satisfied , you can ask your own question)
  • Next, a random character from the range 65 - 90 these are only uppercase Latin letters
  • And a random string

Ascii code table

 3
Author: Стас, 2020-10-29 18:08:59