Генератор рандомных букв python

Как сгенерировать случайную строку в Python?

В этом коротком руководстве мы рассмотрим, как сгенерировать случайную строку в Python. Мы также рассмотрим все возможные типы строк.

Импорт строковых и случайных модулей

Для генерации случайных строк в Python мы используем модули string и random . Модуль string содержит строковые константы Ascii в различных текстовых регистрах, цифрах и т.д. Модуль random , с другой стороны, используется для генерации псевдослучайных значений. В последнем методе мы будем использовать модуль secrets, чтобы помочь нам генерировать криптографически безопасные строки.

Сгенерировать случайную строку Python

Случайные строки обычно генерируются и широко используются. Хотя они обслуживают большое количество вариантов использования, наиболее распространенными из них являются случайные имена пользователей-заполнители, случайные номера телефонов, пароли и т.д.

Модуль string

Прежде чем использовать строковый модуль для генерации случайной строки, давайте посмотрим на различные типы доступных строковых констант.

  1. String.ascii_letters — возвращает строку букв, содержащих различные регистры.
  2. String.ascii_lowercase — возвращает строку с буквами в нижнем регистре.
  3. String.ascii_uppercase — возвращает строку с прописными буквами.
  4. String.digits — возвращает строку, содержащую цифры
  5. String.punctuation — возвращает строку, содержащую знаки препинания. Я перечислил наиболее часто используемые строковые константы. Однако вы можете просмотреть весь список в документации модуля (модуль String).
Читайте также:  Test local html files

Модуль random

Модуль random довольно прост. Он помогает нам выбрать персонажа наугад. Мы используем этот метод для выбора символов из строковой константы.
Однако есть две важные последовательности, о которых вам следует знать:

  1. Random.choices — возвращает элементы в случайном порядке. Здесь персонажи не могут быть уникальными.
  2. Random.sample — возвращает уникальные элементы. Итак, при генерации случайной строки в Python, если вас устраивают повторяющиеся символы, вы можете использовать первый метод, а второй, если вам нужны уникальные символы.

Код и объяснение

import random import string print(random.choices(string.ascii_lowercase)) 

Этот сгенерированный код возвращает один случайный символ. Вы можете изменить метод строковой константы в зависимости от желаемых символов.

Теперь давайте напишем код для генерации строки длиной 5.

import random import string print(''.join(random.choices(string.ascii_lowercase, k=5))) 

Для этого мы передаем еще один аргумент «k», который обозначает размер строки. Этот метод возвращает список символов, поэтому мы используем метод соединения, чтобы преобразовать его в строку.

Строка в разных случаях

В предыдущем методе мы использовали string.ascii_lowercase. Давайте постоянно пробовать буквы, мы также можем объединить два разных типа констант.

Случайная строка в верхнем регистре:

import random import string print(''.join(random.choices(string.ascii_uppercase, k=5))) 
import random import string print(''.join(random.choices(string.ascii_letters, k=5))) 

Объединение различных типов строковых констант:

import random import string print(''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase, k=5))) 

Я не предоставил фрагменты вывода, так как мои результаты будут отличаться от ваших. Кроме того, во всех методах я использовал random.choices. Не стесняйтесь попробовать это, используя также random.sample.

Криптографически безопасные строки

Хотя мы могли бы использовать случайный метод для генерации случайной строки в Python, сгенерированная строка не является криптографически безопасной. Следовательно, не рекомендуется создавать временные пароли.

Python версии 3.6 и выше предлагает лучший способ создания криптографически безопасной случайной строки. Этот метод использует secrets и строковые методы. secrets очень похож на метод random , подробнее о нем вы можете прочитать здесь.

import secrets import string print(''.join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase) for i in range(7))) 

Методы secrets не имеют метода .choices , который принимает второй аргумент. Следовательно, мы используем цикл и получаем диапазон количества символов.

Заключительные мысли

Оба метода можно использовать для генерации случайной строки в Python. Однако то, какой метод вы будете использовать, во многом будет зависеть от вашего варианта использования.

Распространенная ошибка, которую я видел у новичков — это то, что они забывают импортировать модуль перед его использованием. Помните об этом, когда будете практиковаться в использовании методов с другим строковым содержимым.

Источник

Генератор рандомных букв python

Last updated: Feb 22, 2023
Reading time · 4 min

banner

# Table of Contents

# Generate random words in Python

To generate a random word from the file system:

  1. Open a file in reading mode.
  2. Use the str.splitlines() or str.split() method to split the contents of the file into a list.
  3. Use the random.choice() method to pick as many random words from the list as necessary.
Copied!
import random def get_list_of_words(path): with open(path, 'r', encoding='utf-8') as f: return f.read().splitlines() words = get_list_of_words('/usr/share/dict/words') print(words) random_word = random.choice(words) print(random_word) # 👉️ sales

If you’d rather generate random words from a remote database (HTTP request), click on the following subheading:

The code sample generates random words from a file on the local file system.

If you are on Linux or macOS, you can use the /usr/share/dict/words/ file.

If you are on Windows, you can use this MIT word list.

Open the link, right-click on the page and click «Save as», then save the .txt file right next to your Python script.

We used the with statement to open the file in reading mode.

The statement automatically takes care of closing the file for us.

Copied!
import random import requests def get_list_of_words(path): with open(path, 'r', encoding='utf-8') as f: return f.read().splitlines() words = get_list_of_words('/usr/share/dict/words') print(words) random_word = random.choice(words) print(random_word) # 👉️ sales

Make sure to update the path if you aren’t on macOS or Linux.

We used the file.read() method to read the contents of the file into a string.

# Splitting by newlines or splitting by spaces

The str.splitlines method splits the string on newline characters and returns a list containing the lines in the string.

Copied!
multiline_str = """\ bobby hadz com""" lines = multiline_str.splitlines() print(lines) # 👉️ ['bobby', 'hadz', 'com']

If the words in your file are separated by spaces, use the str.split() method instead.

Copied!
string = "bobby hadz . com" lines = string.split() print(lines) # 👉️ ['bobby', 'hadz', '.', 'com']

The str.split() method splits the string into a list of substrings using a delimiter.

When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.

# Picking a random word from the list

If you need to pick a random word from the list, use the random.choice() method.

Copied!
import random def get_list_of_words(path): with open(path, 'r', encoding='utf-8') as f: return f.read().splitlines() words = get_list_of_words('/usr/share/dict/words') print(words) random_word = random.choice(words) print(random_word) # 👉️ unbreakable

The random.choice method takes a sequence and returns a random element from the non-empty sequence.

# Picking N random words from the list

If you need to pick N random words from the list, use a list comprehension.

Copied!
import random def get_list_of_words(path): with open(path, 'r', encoding='utf-8') as f: return f.read().splitlines() words = get_list_of_words('/usr/share/dict/words') print(words) n_random_words = [ random.choice(words) for _ in range(3) ] # 👇️ ['computers', 'praiseworthiness', 'shareholders'] print(n_random_words)

We used a list comprehension to iterate over a range object.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

The range class is commonly used for looping a specific number of times.

On each iteration, we call the random.choice() method to pick a random word and return the result.

# Generate random words from a remote database (HTTP request)

To generate random words from a remote database:

  1. Make an HTTP request to a database that stores a word list.
  2. Use the random.choice() method to pick a random word from the list.
  3. Optionally, use a list comprehension to pick N random words from the list.
Copied!
import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) random_word = random.choice(words) print(random_word) # 👉️ zoo

If you don’t have the requests module installed, install it by running the following command.

Copied!
# 👇️ in a virtual environment or using Python 2 pip install requests # 👇️ for python 3 (could also be pip3.10 depending on your version) pip3 install requests

You can open the MIT word list in your browser to view the contents.

The list contains 10,000 words with each word on a separate line.

We used the bytes.decode() method to convert the bytes object to a string.

The bytes.decode method returns a string decoded from the given bytes. The default encoding is utf-8 .

The words are on separate lines, so we used the str.splitlines() method to split the string into a list of words.

If your database responds with a long string containing space-separated words, use the str.split() method instead.

Copied!
string = "bobby hadz . com" lines = string.split() print(lines) # 👉️ ['bobby', 'hadz', '.', 'com']

# Picking a random word from the list

If you need to pick a random word from the list, use the random.choice() method.

Copied!
import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) random_word = random.choice(words) print(random_word) # 👉️ global

# Picking N random words from the list

If you need to pick N random words from the list, use a list comprehension.

Copied!
import random import requests def get_list_of_words(): response = requests.get( 'https://www.mit.edu/~ecprice/wordlist.10000', timeout=10 ) string_of_words = response.content.decode('utf-8') list_of_words = string_of_words.splitlines() return list_of_words words = get_list_of_words() print(words) n_random_words = [ random.choice(words) for _ in range(3) ] # 👇️ ['clerk', 'trust', 'tr'] print(n_random_words)

The list comprehension iterates over a range object of length N and calls the random.choice() method to pick a random word on each iteration.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью