Uppercase every other word in a string using split/join

Question:

I have a string:

string = "Hello World" 

That needs changing to:

"hello WORLD" 

Using only split and join in Python.

Any help?

string = "Hello World" 

split_str = string.split()

Can’t then work out how to get first word to lowercase second word to uppercase and join

Asked By: Darren Woodcock

||

Answers:

The code below works for any number of words:

string = "Hello World"
words   =  string.split() # works also for multiple spaces and tabs
result  =  ' '.join((w.upper() if i&1 else w.lower()) for i,w in enumerate(words))
print(result)
# "hello WORLD"
Answered By: C-3PO

for many words:

make a list of words using split

connect everything with " " using join

inside we run through the list using i up to the length of this list

if this is an odd number, then upper otherwise lower (because the list is numbered from 0, and we need every second one)

string = "Hello World! It is Sparta!"
split_str  = string.split()
print(" ".join(split_str[i].upper() if i&1 else split_str[i].lower() for i in range(len(split_str))))

# hello WORLD! it IS sparta!

for two words (easy solution):

string = "Hello World"
split_str  = string.split()
print(' '.join([split_str[0].lower(),split_str[1].upper()]))

# hello WORLD
Answered By: Slonsoid

OP’s objective cannot be achieved just with split() and join(). Neither of those functions can be used to convert to upper- or lower-case.

The cycle class from the itertools module is ideal for this:

from itertools import cycle

words = 'hello world'

CYCLE = cycle((str.lower, str.upper))

print(*(next(CYCLE)(word) for word in words.split()))

Output:

hello WORLD
Answered By: DarkKnight
string = str(input("Enter any sentence here: "))      #prompt user for input

split_string = string.split()                         #to store the split string -creates a list

final_string = ""                                     #to compile the resulting string

for i in range(len(split_string)):                      #for loop for repeat operation

    if i % 2 == 0:
        final_string += split_string[i].upper() + " "   #if item index divides by 2 then convert to uppercase

    else:
        final_string += split_string[i].lower() + " "   #otherwise convert to lowercase

print(final_string)
Answered By: user21517560