Как в питоне задать рандомную строку

от admin

Генерация рандомной строки

Меня интересует, как можно генерировать строку вида sa32Asf7w1 с помощью библиотеки random в python. Первые 4 символа — рандомный набор букв и цифр, с 6 по 10 то же самое. 5 символ — рандомная заглавная буква.

как вариант — сделайте словарь букв и цифр и выбирайте оттуда, а 5 символ выберите из отдельного словаря (где только большие буквы) или из того же словаря, только с границами, соответствующими большие буквы

итоговый вариант:

да, через choice компактнее код

или так (еще на длине немного сэкономить) 🙂 :

Zhihar's user avatar

Странно, что до сих пор никто не привёл самого Pythonic решения:

Mikhail Murugov's user avatar

Могу предложить что-то вроде такого:

В принципе все просто:

  • Функция getRandStr(lenght) генерирует случайные символы (на основе их ascii кодов, диапазон от 33 до 125 это латинские буквы, цифры, знаки препинания. Если не устраивает — можете задать свой)
  • Далее случайный символ из диапазона 6590 это только заглавные латинские буквы
  • И еще случайная строка

Таблица ascii кодов

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.3.11.43304

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

Generate Random Strings and Passwords in Python

In this lesson, you will learn how to create a random string and passwords in Python.

Table of contents

String Constants

Below is the list of string constants you can use to get a different set of characters as a source for creating a random string.

How to Create a Random String in Python

We can generate the random string using the random module and string module. Use the below steps to create a random string of any length in Python.

    Import string and random module

The string module contains various string constant which contains the ASCII characters of all cases. It has separate constants for lowercase, uppercase letters, digits, and special symbols, which we use as a source to generate a random string.
Pass string constants as a source of randomness to the random module to create a random string

The string.ascii_lowercase returns a list of all the lowercase letters from ‘a’ to ‘z’. This data will be used as a source to generate random characters.

Decide how many characters you want in the resultant string.

Run a for loop till the decided string length and use the random choice() function in each iteration to pick a single character from the string constant and add it to the string variable using a join() function. print the final string after loop competition

Use the string.ascii_letters , string.digits , and string.punctuation constants together to create a random password and repeat the first four steps.

Example to generate a random string of any length

Output:

  • The random choice() function is used to choose a single item from any sequence and it can repeat characters.
  • The above random strings contain all lower case letters. If you want only the uppercase letters, then use the string.ascii_uppercase constant instead in the place of a string.ascii_lowercase .

Random String of Lower Case and Upper Case Letters

In Python, to generate a random string with the combination of lowercase and uppercase letters, we need to use the string.ascii_letters constant as the source. This constant contains all the lowercase and uppercase letters.

Example

Output:

Random string of specific letters

If you wanted to generate a random string from a fixed set of characters, please use the following example.

Random String without Repeating Characters

Note: The choice() method can repeat characters. If you don’t want repeated characters in a resultant string, then use the random.sample() method.

Warning : As you can see in the output, all characters are unique, but it is less secure because it will reduce the probability of combinations of letters because we are not allowing repetitive letters and digits.

Create Random Password with Special characters, letters, and digits

A password that contains a combination of characters, digits, and special symbols is considered a strong password.

Assume, you want to generate a random password like: –

  • ab23cd#$
  • jk%m&l98
  • 87t@h*ki

We can generate a random string password in Python with letters, special characters, and digits using the following two ways.

Похожие статьи