Reputation: 301
I was wondering if there is a random letter generator in Python that takes a range as parameter? For example, if I wanted a range between A and D? I know you can use this as a generator:
import random
import string
random.choice(string.ascii_letters)
But it doesn't allow you to supply it a range.
Upvotes: 10
Views: 14607
Reputation: 44525
You can build your own letter range iterator and choose from it randomly:
import random
def letter_range(start, stop, step=1):
"""Yield a range of lowercase letters.
Examples
--------
>>> list(letter_range("a", "f"))
['a', 'b', 'c', 'd', 'e']
>>> list(letter_range("a", "f", step=2))
['a', 'c', 'e']
"""
start = ord(start.lower())
stop = ord(stop.lower())
for ord_ in range(start, stop, step):
yield chr(ord_)
letters = list(letter_range("a", "g"))
random.choice(letters)
# "e"
Upvotes: 0
Reputation: 685
Saw this and thought the algorithm I just wrote might be helpful. This generates a random uppercase ascii string of N length:
from random import randint
def generate_random_nlength_string(n):
prandstr = [chr(randint(65,90)) for _ in range(n)]
return ''.join(prandstr)
Upvotes: 2
Reputation: 142
Using your original way of getting a random letter you can simply make a function as such.
def getLetter(start, stop):
letter = random.choice(string.ascii_letters)
while letter < start and letter > stop:
letter = random.choice(string.ascii_letters)
return letter
Calling it like getLetter('a', 'd')
Upvotes: 1
Reputation: 28606
>>> random.choice('ABCD')
'C'
Or if it's a larger range so you don't want to type them all out:
>>> chr(random.randint(ord('I'), ord('Q')))
'O'
Upvotes: 3
Reputation: 95509
You can trivially define such a thing:
def letters_in_range(start_letter, end_letter):
start_index = string.ascii_letters.find(start_letter)
end_index = string.ascii_letters.find(end_letter)
assert start_index != -1
assert end_index != -1
assert start_letter < end_letter
return string.ascii_letters[start_index:end_index]
With the above:
random.choice(letters_in_range('A', 'D'))
Upvotes: 1
Reputation: 2907
You can slice string.ascii_letters
:
random.choice(string.ascii_letters[0:4])
Upvotes: 12
Reputation: 2711
String slicing would be my solution to this
random.choice(string.ascii_letters[:4])
This would randomly choose one of the first 4 letters of the alphabet. Obviously 4 could be any value.
Upvotes: 4
Reputation: 76297
The function choice
takes a general sequence.
Return a random element from the non-empty sequence seq.
In particular
random.choice(['A', 'B', 'C', 'D'])
will do what you want.
You can easily generate the range programatically:
random.choice([chr(c) for c in xrange(ord('A'), ord('D')+1)])
Upvotes: 3
Reputation: 41
Ascii is represented with numbers, so you can random a number in the range that you prefer and then cast it to char.
Upvotes: 5