Search code examples
pythonjoinsplituppercaselowercase

Uppercase every other word in a string using split/join


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


Solution

  • 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"