Search code examples
pythonarrayslistuppercaselowercase

how to replace uppercase and lowercase letters in words alternately in a sentence? Python


I am new to Python programming. I'm trying to learn about lists.

I want to create a new program that can convert each word into uppercase and lowercase letters alternately in a sentence.

I’m stuck here:

input_text = "hello my name is rahul and i'm from india"
result = ""
myArr = input_text.split(' ')

for idx in range(len(myArr)):
  if idx % 2 == 0 :
    result = result + myArr[idx].upper()
  else:
    result = result + myArr[idx].lower()

print(str(result))

With this code I can get, for example:

input : "hello my name is rahul and i'm from india"
output : "HELLOmyNAMEisRAHULandI'MfromINDIA"

but what I am trying to get is:

input : "hello my name is rahul and i'm from india"
output : "HELLO my NAME is RAHUL and I'M from INDIA"

I want to add a space to each word in the sentence.


Solution

  • You've sort of got it -- the best way to do this is to add the capitalized/lowercased words to a list, then use .join() to turn the word list into a string with each word separated by a space:

    input_text = "hello my name is rahul and i'm from india"
    result = ""
    myArr = input_text.split(' ')
    words = []
    for idx in range(len(myArr)):
      if idx % 2 == 0 :
        words.append(myArr[idx].upper())
      else:
        words.append(myArr[idx].lower())
    
    result = ' '.join(words)
    print(result)
    

    Contrary to what other answerers have suggested, using repeated concatenation is a bad idea for efficiency reasons.