Home python generation of random string

generation of random string




I am interested in how to generate a row of the type 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 Symbol – Random Capital Letter.

Answer 1, Authority 100%

As an option – Make a dictionary of letters and numbers and select from there, and select 5 characters from a separate dictionary (where only big letters) or from the same dictionary, only with borders corresponding to large letters

Final Option:

import random
Import String
Text = [Random.Choice + String.Digits if i! = 5 Else String.asci_uppercase) for i in range (10)]
Print (''. Join (Text))


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))


Yes, via Choice Comparate code

import random
Text = [Random.Choice ('ABC123') for _ in range (10)]
TEXT [5] = Random.Choice ('ABC')
Print (''. Join (Text))

or in general:

text = [random.choice ('abc123') if i! = 5 Else Random.Choice ('ABC' ) For i in Range (10)]
Print (''. Join (Text))

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

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

Answer 2, Authority 71%

from random import choice
Import String
all = string.ascii_lowercase + string.digits
Five = string.ascii_uppercase.
Print (''. Join (Choice for _ in Range (5)) + Choice (Five) + '' .join (Choice for _ in Range (6, 11)))

Answer 3, Authority 71%

It is strange that so far no one has led 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)) # first choose 4 of any letters / numbers
res + = Choice # one uppercase letter
res + = '' .join (choices (letters_and_digits, k = 5)) # more 5 letters or numbers

Answer 4, Authority 43%

I can offer 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)

In principle, everything is simple:

  • getRandstr (Lenght) generates random symbols (based on their ASCII codes, range from 33 to 125 These are Latin letters, numbers, punctuation signs. If not satisfied – you can set your own)
  • Next Random Symbol from the range 65 90 It is only capital Latin letters
  • and another random line

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions