Is there a random letter generator with a range?

I was wondering if there is a random letter generator in Python that takes a range as a parameter? For example, if I need a range between A and D? I know that you can use this as a generator:

import random import string random.choice(string.ascii_letters) 

But this does not allow you to specify a range.

+7
python
source share
8 answers

You can slice string.ascii_letters :

 random.choice(string.ascii_letters[0:4]) 
+9
source share

Ascii is represented by numbers, so you can arbitrarily select a number in the range that you prefer, and then translate it to char.

+4
source share

The choice function takes a general sequence.

Returns a random element from a non-empty sequence seq.

In particular,

 random.choice(['A', 'B', 'C', 'D']) 

will do what you want.

You can easily generate a range programmatically:

 random.choice([chr(c) for c in xrange(ord('A'), ord('D')+1)]) 
+3
source share

Line cutting will be my solution for this

 random.choice(string.ascii_letters[:4]) 

This randomly selects one of the first four letters of the alphabet. Obviously, 4 can be any value.

+3
source share
 >>> random.choice('ABCD') 'C' 

Or, if it's a larger range, so you don't want to type everything:

 >>> chr(random.randint(ord('I'), ord('Q'))) 'O' 
+2
source share

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')) 
+1
source share

Using your original way of getting a random letter, you can simply create 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 

Call as getLetter('a', 'd')

+1
source share

I saw this and thought that the algorithm I just wrote might be useful. This generates a random ascii string string of length N:

 from random import randint def generate_random_nlength_string(n): prandstr = [chr(randint(65,90)) for _ in range(n)] return ''.join(prandstr) 
+1
source share

All Articles