I need help with python program. I don’t know how to make python change at least 1 lowercase letter to uppercase.
JavaScript
x
13
13
1
from random import *
2
import random
3
4
pin=""
5
lenght=random.randrange(8,15)
6
7
for i in range(lenght):
8
pin=pin+chr(randint(97,122))
9
10
11
print(pin)
12
13
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.
JavaScript
1
15
15
1
import random
2
import string
3
4
# randomize length of password
5
length = random.randrange(8, 15)
6
7
# create a list of random lowercase letters
8
characters = [random.choice(string.ascii_lowercase) for _ in range(length)]
9
10
# select the indexes that will be changed to uppercase characters
11
index_upper = random.sample(range(0, length), random.randrange(1, length))
12
13
# construct the final pin
14
pin = ''.join(c.upper() if i in index_upper else c for i, c in enumerate(characters))
15
You can check what’s going on if you print
the variables
JavaScript
1
5
1
print(length)
2
print(characters)
3
print(index_upper)
4
print(pin)
5
Example output:
JavaScript
1
5
1
13
2
['y', 'g', 'u', 'k', 't', 'a', 'w', 'a', 'g', 'f', 'f', 'x', 'p']
3
[2, 7, 4, 0, 5, 6, 1]
4
YGUkTAWAgffxp
5
If you’re not familiar with the generator syntax where pin
is build, it roughly translates to:
JavaScript
1
7
1
pin = ''
2
for i, c in enumerate(characters):
3
if i in index_upper:
4
pin += c.upper()
5
else:
6
pin += c
7