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

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(str(result))

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


Using a list comprehension we can try:

input_text = "hello my name is rahul and i'm from india"
words = input_text.split()
output = ' '.join([x.upper() if ind % 2 == 0 else x for ind, x in enumerate(words)])
print(output)  # HELLO my NAME is RAHUL and I'M from INDIA

You can add all the values to a list and finally join them using the str.join method.

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:
        res = myArr[idx].upper()
    else:
        res = myArr[idx].lower()
    result.append(res)

print(" ".join(result))

Output:

HELLO my NAME is RAHUL and I'M from INDIA