-3

I want to make a list / array with letters and then have my program pick one of them but I want it to be lower and uppercase randomly

I can use this:

list = "A", "a", "B", "b"
print(random.choice(list))

but is there a way to just add one letter to list and then have the program do the randomization of uppercase randomly

verbids
  • 55
  • 6
  • 1
    `random.choice(string.ascii_letters)`…? – deceze Jun 24 '19 at 07:43
  • 3
    Don't overwrite the builtin `list` with a variable of the same name (that isn't even a list). – Matthias Jun 24 '19 at 07:43
  • `is there a way to just add one letter to list` , does that mean you want to only add lower letters and pick either lower or upper letters randomly – Devesh Kumar Singh Jun 24 '19 at 07:48
  • It is unclear what you are asking. Include a desired input/output behavior rather than keeping things unclear. This saves everyone's time, including your own – Sheldore Jun 24 '19 at 07:50

3 Answers3

2

You can create the list of uppercase characters using str.upper and do random.choice on that.

Also since list is a python builtin name, don't use it as a variable

import random

#List of lowercase characters
li = ["a", "b"]

#Add list of all uppercase characters to original list
li += [item.upper() for item in li]
#['a', 'b', 'A', 'B']

print(random.choice(li))

In addition, there is a simpler way to do it without having a need to create a list of all the letters, as per @deceze in the comments, by using string.ascii_letters, which is a list of uppercase and lowercase ascii letters

import string
print(random.choice(string.ascii_letters))
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
0

You can write a simple function to do that for every letter or a complete text:

import random

def random_case(text):
    return text.upper() if random.randint(0,1) == 1 else text.lower()

your_list.append(random_case("a"))
Florian H
  • 3,052
  • 2
  • 14
  • 25
0

I am providing a solution in case you can have both uppercase and lowercase letters in your initial list and you want to cover every option. The idea is that you randomly pick one and then you randomly choose to capitilize it or make it lower.

from random import choice, getrandbits

res = choice(my_letters).lower() if getrandbits(1) else choice(my_letters).capitalize()

So assuming:

my_letters = ['x', 'L']

you could get all 4 of 'x', 'X', 'L' and 'l' with the same probability.


Note that the reason I am using getrandbits is described in detail here

Ma0
  • 15,057
  • 4
  • 35
  • 65