Генерация рандомной строки
Меня интересует, как можно генерировать строку вида sa32Asf7w1 с помощью библиотеки random в python. Первые 4 символа — рандомный набор букв и цифр, с 6 по 10 то же самое. 5 символ — рандомная заглавная буква.
как вариант — сделайте словарь букв и цифр и выбирайте оттуда, а 5 символ выберите из отдельного словаря (где только большие буквы) или из того же словаря, только с границами, соответствующими большие буквы
итоговый вариант:
да, через choice компактнее код
или так (еще на длине немного сэкономить) 🙂 :
![]()
Странно, что до сих пор никто не привёл самого Pythonic решения:
![]()
Могу предложить что-то вроде такого:
В принципе все просто:
- Функция getRandStr(lenght) генерирует случайные символы (на основе их ascii кодов, диапазон от 33 до 125 это латинские буквы, цифры, знаки препинания. Если не устраивает — можете задать свой)
- Далее случайный символ из диапазона 65 — 90 это только заглавные латинские буквы
- И еще случайная строка

Дизайн сайта / логотип © 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.
- Combine the following three constants and use them as a data source for the random.choice() function to select random characters from it.
- string.ascii_letters : To include letters from a-z and A-Z
- string.digits : To include digits from 1 to 10
- string.punctuation : to get special symbols
Example
Output:
Using the string.printable
Output
Random password with a fixed count of letters, digits, and symbols
It is a widespread use case that passwords must contain some count of digits and special symbols.
Let’s see how to generate a random password that contains at least one lowercase letter, one uppercase letter, one digit, and one special symbol.
Steps: –
- First, select the number of random lowercase and uppercase letters specified
- Next, choose the number of random digits
- Next, choose the number of special symbols
- Combine both letters, digits, and special symbols into a list
- At last shuffle the list
- Convert list back to a string
Generate a secure random string and password
Above all, examples are not cryptographically secure. The cryptographically secure random generator generates random data using synchronization methods to ensure that no two processes can obtain the same data simultaneously.
If you are producing random passwords or strings for a security-sensitive application, then you must use this approach.
If you are using Python version less than 3.6, then use the random.SystemRandom().choice() function instead of random.choice() .
If you are using a Python version higher than 3.6 you can use the secrets module to generate a secure random password.
Use secrets.choice() function instead of random.choice()
Generate a random alphanumeric string of letters and digits
We often want to create a random string containing both letters and digits such as ab23cd, jkml98, 87thki. In such cases, we use the string.ascii_letters and string.digits constants to get the combinations of letters and numbers in our random string.
Now, let’s see the to create a random string with the combination of a letter from A-Z, a-z, and digits 0-9.
Random alphanumeric string with a fixed count of letters and digits
For example, I want to create a random alpha-numeric string that contains 5 letters and 3 numbers.
Example
Output:
Generate a random string token
The above examples depend on String constants and random module functions. There are also other ways to generate a random string in Python. Let see those now.
We can use secrets.token_hex() to get a secure random text in hexadecimal format.
Output:
Generate universally unique secure random string Id
The random string generated using a UUID module is suitable for the Cryptographically secure application. The UUID module has various functions to do this. Here in this example, we are using a uuid4() function to generate a random string Id.
Use the StringGenerator module to generate a random string
The StringGenerator module is not a part of a standard library. However, if you want you can install it using pip and start using it.
- pip install StringGenerator .
- Use a render() function of StringGenerator to generate randomized strings of characters using a template
Let see the example now.
Next Steps
I want to hear from you. What do you think of this article? Or maybe I missed one of the ways to generate random string in Python. Either way, let me know by leaving a comment below.
Also, try to solve the random module exercise and quiz to have a better understanding of working with random data in Python.
Practice Problem
Create a random alphanumeric string of length ten that must contain at least four digits. For example, the output can be anything like 1o32WzUS87, 1P56X9Vh87
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
How to Generate Random Strings in Python

In this article, we’ll take a look at how we can generate random strings in Python. As the name suggests, we need to generate a random sequence of characters, it is suitable for the random module.
There are various approaches here, so we’ll start from the most intuitive one; using randomized integers.
Build a string from a random integer sequence
As you may know, the chr(integer) maps the integer to a character, assuming it lies within the ASCII limits. (Taken to be 255 for this article)
We can use this mapping to scale any integer to the ASCII character level, using chr(x) , where x is generated randomly.
Sample Output
Here, while the length of the string seems to be 10 characters, we get some weird characters along with newlines, spaces, etc.
This is because we considered the entire ASCII Character set.
If we want to deal with only English alphabets, we can use their ASCII values.
Sample Output
As you can see, now we have only upper and lowercase letters.
But we can avoid all this hassle, and have Python do the work for us. Python has given us the string module for exactly this purpose!
Let’s look at how we can do the same this, using just a couple of lines of code!
Generate Random Strings in Python using the string module
The list of characters used by Python strings is defined here, and we can pick among these groups of characters.
We’ll then use the random.choice() method to randomly choose characters, instead of using integers, as we did previously.
Let us define a function random_string_generator() , that does all this work for us. This will generate a random string, given the length of the string, and the set of allowed characters to sample from.
Here, we have specified the allowed list of characters as the string.ascii_letters (upper and lowercase letters), along with string.punctuation (all punctuation marks).
Now, our main function was only 2 lines, and we could randomly choose a character, using random.choice(set) .
Sample Output
We have indeed generated a random string, and the string module allows easy manipulations between character sets!
Make the random generation more secure
While the above random generation method works, if you want to make your function be more cryptographically secure, use the random.SystemRandom() function.
An example random generator function is shown below:
Output
This ensures that your string generation is cryptographically secure.
Random UUID Generation
If you want to generate a random UUID String, the uuid module is helpful for this purpose.
Sample Output
Conclusion
In this article, we learned how we could generate random strings in Python, with the help of the random and string modules.
Generate Random Text In Python With NumPy And String Formatting
Howdy folks! Today we’re talking randomness and text generation. But fear not, this won’t be a complex natural-language processing (NLP) approach to text generation. Instead, we’ll be diving into using NumPy and string formatting with Python to generate simple randomized text blocks. As an example, I’ll be using bits of code from a Dungeons & Dragons project I’m working on that randomly generates spells for the game. You won’t need to know about D&D to follow along, though.
Random Choice With NumPy
Okay, so first let’s talk libraries. The only one we’ll need here is NumPy, which has all sorts of tools for computation, arrays, and other high-level math. It also, and most importantly, has a module called “random” that we’ll be using. Let’s import NumPy now:
Inside the “random” module are a couple key functions. Today we’ll be using numpy.random.choice() which randomly selects an option from a list, but there are a couple dozen others that give us normal distributions, random numbers within an integer range, and so on. In practice, choice() looks like this:
Great! We’ve seen that we can pass it a list, and it will return an item. Let’s say instead that this is a list of strings, and we want some of them to occur more often than others. This could be thought of (again in the context of D&D or video games) like a rarity system for finding treasure. For that, choice() also has a solution! We simply pass in a new argument p that stands for probability. The only requirement here is that our p is a list of equal length to our list of items, and that it be made up of floats that add exactly to 1. For example:
We know — because of probability — that we are only going to get the result “legendary” about 2 times in every 100 attempts. We’ll get “common” about 40 times in the same number of goes. We’ll use this knowledge to drive our text generator, so that we can tweak which values are more or less likely in any given spell it creates. And in order to do that, we need to talk about string formatting in Python.
F-String Formatting In Python
So, Python has had ways in the past for strings to be more flexible. By that I mean that you could have one default sort of “formula” string, and fill it in like Mad Libs as you go. This was done with %-formatting and also the method str.format() , but they’re both kinda clunky and hard to read. Allow me:
From a user-side this doesn’t matter a whole lot, since we get the same end sentence, but the code just gets so clunky. And if you’re thinking “Well why don’t we just put the final words within .format() instead of assigning them previously? That’d save four lines!” you’re making a sound point, but remember: This is building towards modularity. In practice we won’t have set values like “sentence” or “harder”, but rather randomly-generated ones. If we were to assign all those within .format() it would be even clunkier than now!
So how do we remedy this? With an f-string in Python, we do the same exact thing, but with a single character instead. Everything in .format() gets removed and we add an f before our string. This turns the previous example into:
It seems our output sentence no longer rings true. Thanks f-strings! With this under our belt, we can combine the two and make some funky, unpredictable text.
Putting It All Together
So far we’ve seen how to use NumPy to generate random values and set the likelihood of getting those values. We’ve also seen how to insert variables into a string. We can now combine these two skills into a spell generator (or really any generator you like). First, let’s make up some word banks that’d be fun to pull from:
These will be the fillers in our little Pythonic Mad Lib. With them in hand we’re ready to make our final function:
When we call the function random_spell() we get results like:
And that’s it! Congratulations, you now know how to use f-strings and random selection to create new text. But this is just the beginning. You can expand this to the paragraph level and even move on having certain sentences be completely optional. We could have a clause like:
This adds a little more unpredictability and flair. And the options are endless. Feel free to explore the repo where I’m working on the bigger version of this here or shoot me a message on Twitter @zych_steven! Send me your weirdest text.