Is there a way to check if a string has a capital letter and if so change the first letter of the second word to capital in Python? [closed]

I’ve got a piece of code that creates a string in an encoded format and I’m trying to check whether the original message has a capital letter and if so change the number character into a capital letter, here is my current code:

characterNumber = 0
  for character in message:
    characterNumberWord = 0
    characterNumber += 1
    if character.isupper():        
      while characterNumberWord != 1:
        characterNumberWord += 1
        string3 += string2.upper()
    else:
      string3 += character

For an example imagine message is ‘Hello’ and string2 is ‘jfnmq’. I want the outputted code to be Jfnmq. Fyi this code is a Ceaser Cipher and it changes every second letter.

Answer

If your question is to find uppercase characters in message and change the corresponding letter in string2 to uppercase:

message = 'HeLlO'  # uppercase H, L, O
string2 = 'jfnmq'
string3 = []
for l, c in zip(message, string2):
    if l.isupper():
        string3.append(c.upper())
    else:
        string3.append(c)

print(''.join(string3))
# JfNmQ
  • zip lets you iterate over multiple sequences together, giving the Nth item from each sequence, as a tuple. So l is from message and c is from string2.

  • Then check each l to see if it’s uppercase, and if so, add the uppercased version of the corresponding letter c (from string2) to the list string3. If not upper case, then add the c as is.

  • The join() at the end each of the items in the list, the letters in string3 (which is initialised to a list)

The loop can be shortened to this slightly clearer code:

for l, c in zip(message, string2):
    string3.append(c.upper() if l.isupper() else c)

print(''.join(string3))

Or even this one-liner (not-recommended, for lack of readability):

string3 = [c.upper() if l.isupper() else c for l, c in zip(message, string2)]
# or just
''.join(c.upper() if l.isupper() else c for l, c in zip(message, string2))