Generate a random letter in Python
Simple:
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> import random
>>> random.choice(string.ascii_letters)
'j'
string.ascii_letters
returns a string containing the lower case and upper case letters according to the current locale.
random.choice
returns a single, random element from a sequence.
Random string generation with upper case letters and digits
Answer in one line:
''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
or even shorter starting with Python 3.6 using random.choices()
:
''.join(random.choices(string.ascii_uppercase + string.digits, k=N))
A cryptographically more secure version: see this post
''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))
In details, with a clean function for further reuse:
>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'
How does it work ?
We import string
, a module that contains sequences of common ASCII characters, and random
, a module that deals with random generation.
string.ascii_uppercase + string.digits
just concatenates the list of characters representing uppercase ASCII chars and digits:
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
Then we use a list comprehension to create a list of 'n' elements:
>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']
In the example above, we use [
to create the list, but we don't in the id_generator
function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this here).
Instead of asking to create 'n' times the string elem
, we will ask Python to create 'n' times a random character, picked from a sequence of characters:
>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'
Therefore random.choice(chars) for _ in range(size)
really is creating a sequence of size
characters. Characters that are randomly picked from chars
:
>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']
Then we just join them with an empty string so the sequence becomes a string:
>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'
Python: Generate random letter then Keystroke said letter
There are many ways to achieve this, but here is one:
import random, string, keyboard
random_letter = random.choice(string.ascii_letters)
keyboard.write(random_letter)
The random letter can be both lower and upper case in this example because string.ascii_letters returns:
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
(you may have to pip install the keyboard library)
How to generate random character from more than one source in Python?
Just make a source with all the things you want:
import random
import string
source = string.ascii_letters + string.punctuation + string.digits
for i in range(0,4):
print(random.choice(source))
Prints:
E
)
2
h
Is there a random letter generator with a range?
You can slice string.ascii_letters
:
random.choice(string.ascii_letters[0:4])
Generating random characters in Python
One approach:
import random
import string
# select 2 digits at random
digits = random.choices(string.digits, k=2)
# select 9 uppercase letters at random
letters = random.choices(string.ascii_uppercase, k=9)
# shuffle both letters + digits
sample = random.sample(digits + letters, 11)
result = "NAA3U" + ''.join(sample)
print(result)
Output from a sample run
NAA3U6MUGYRZ3DEX
If the code needs to contain at least 3 digits, but is not limited to this threshold, just change to this line:
# select 11 uppercase letters and digits at random
letters = random.choices(string.ascii_uppercase + string.digits, k=11)
this will pick at random from uppercase letters and digits.
How do I remove a random letter from a string in python?
You can do it with random.choice()
:
import random
string = "Hello world"
string.replace(random.choice(string), '')
Output:
'Hello wold'
Is there a possibility to write a random letter generator as short as in python?
If "short" just means one line, then any of these would do:
char letter = "abcdefghijklmnopqrstuvwxyz".charAt((int) (Math.random() * 26));
char letter = (char) ThreadLocalRandom.current().nextInt('a', 'z'+1);
char letter = (char) ('a' + Math.random() * 26);
Related Topics
Correct Way to Define Class Variables in Python
How to Convert a Numpy Array to Pil Image Applying Matplotlib Colormap
Multiprocessing in Python - Sharing Large Object (E.G. Pandas Dataframe) Between Multiple Processes
Matplotlib Savefig() Plots Different from Show()
Product Code Looks Like Abcd2343, How to Split by Letters and Numbers
Removing Index Column in Pandas When Reading a CSV
The Problem with Installing Pil Using Virtualenv or Buildout
Sorting Python List Based on the Length of the String
Solving "Dll Load Failed: %1 Is Not a Valid Win32 Application." for Pygame
How to Make Python Requests Work via Socks Proxy
In-Memory Size of a Python Structure
Programmatically Searching Google in Python Using Custom Search
Imports in _Init_.Py and 'Import As' Statement
What Version of Visual Studio Is Python on My Computer Compiled With
No Module Named 'Polls.Apps.Pollsconfigdjango'; Django Project Tutorial 2