Home > Back-end >  Python change lowercase to uppercase
Python change lowercase to uppercase

Time:11-08

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)

CodePudding user response:

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

CodePudding user response:

import random

pin = []
length = random.randrange(8, 15)

for i in range(length):
    pin.append(chr(random.randint(97, 122)))

number_of_uppercase_chars = random.randint(0, length)

for i in range(number_of_uppercase_chars):
    char_index = random.randint(0, length - 1)
    pin[char_index] = pin[char_index].upper()


pin = "".join(pin)
print(pin)

CodePudding user response:

from random import *
import random


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

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

print(pin)

pin = pin.upper()

while not any(c for c in pin if c.islower()):
    pin = pin.lower()
    pin = "".join(random.choice([k.upper(), k ]) for k in pin )

print(pin)

CodePudding user response:

I give it a shot with the little info I got. You can change a lower to upper char with lower(), and vise versa with upper().

pin="asd"

print(pin.upper())
>>>ASD

This applies of course to single characters as well. Since idk what the exact goal is, I gave above example. If you want to be sure some character in pin is upper, you can apply it to one character. An example to change the 6th character to upper:

pin=pin[:5] pin[5].upper() pin[6:]
  • Related