Home > OS >  Uppercase every other word in a string using split/join
Uppercase every other word in a string using split/join

Time:11-13

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

CodePudding user response:

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

CodePudding user response:

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"

CodePudding user response:

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