Skip to content
Advertisement

Python change lowercase to uppercase

I need help with python program. I don’t know how to make python change at least 1 lowercase letter to uppercase.

from random import *
import random

pin=""
lenght=random.randrange(8,15)

for i in range(lenght):
    pin=pin+chr(randint(97,122))


print(pin)

Advertisement

Answer

You want a password with at least one uppercase letter but it shouldn’t be every character. First get length random lowercase letters. Then get some random indexes (min. 1, max. length-1) that should be transposed to uppercase.

import random
import string

# randomize length of password
length = random.randrange(8, 15)

# create a list of random lowercase letters
characters = [random.choice(string.ascii_lowercase) for _ in range(length)]

# select the indexes that will be changed to uppercase characters
index_upper = random.sample(range(0, length), random.randrange(1, length))

# construct the final pin
pin = ''.join(c.upper() if i in index_upper else c for i, c in enumerate(characters))

You can check what’s going on if you print the variables

print(length)
print(characters)
print(index_upper)
print(pin)

Example output:

13
['y', 'g', 'u', 'k', 't', 'a', 'w', 'a', 'g', 'f', 'f', 'x', 'p']
[2, 7, 4, 0, 5, 6, 1]
YGUkTAWAgffxp

If you’re not familiar with the generator syntax where pin is build, it roughly translates to:

pin = ''
for i, c in enumerate(characters):
    if i in index_upper:
        pin += c.upper()
    else:
        pin += c
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement