how to upper case every other word in string in python

Question:

I am wondering how to uppercase every other word in a string. For example, i want to change “Here is my dog” to “Here IS my DOG”
Can anyone help me get it started? All i can find is how to capitalize the first letter in each word.

Asked By: Neal Wang

||

Answers:

I think the method you are looking for is upper().
You can use split() to split your string into words and the call upper() on every other word and then join the strings back together, using join()

' '.join( w.upper() if i%2 else w
          for (i, w) in enumerate(sentence.split(' ')) )
Answered By: Marcelo Cantos

It’s not the most compact function but this would do the trick.

string = "Here is my dog"

def alternateUppercase(s):
    i = 0
    a = s.split(' ')
    l = []
    for w in a:
        if i:
            l.append(w.upper())
        else:
            l.append(w)
        i = int(not i)
    return " ".join(l)

print alternateUppercase(string)
Answered By: enderskill
words = sentence.split(' ')
sentence = ' '.join(sum(zip(words[::2], map(str.upper, words[1::2])), ()))
Answered By: Karl Knechtel

Another method that uses regex to handle any non-alphanumeric characters.

import re

text = """The 1862 Derby was memorable due to the large field (34 horses), 
the winner being ridden by a 16-year-old stable boy and Caractacus' 
near disqualification for an underweight jockey and a false start."""

def selective_uppercase(word, index):
    if  index%2: 
        return str.upper(word)
    else: 
        return word

words, non_words =  re.split("W+", text), re.split("w+", text)
print "".join(selective_uppercase(words[i],i) + non_words[i+1] 
              for i in xrange(len(words)-1) )

Output:

The 1862 Derby WAS memorable DUE to THE large FIELD (34 HORSES), 
the WINNER being RIDDEN by A 16-YEAR-old STABLE boy AND Caractacus' 
NEAR disqualification FOR an UNDERWEIGHT jockey AND a FALSE start.
Answered By: Bora Caglayan
user_word_2 = "I am passionate to code"


#block code to split the sentence
user_word_split_2 = user_word_2.split()   


#Empty list to store a to be split list of words, 

words_sep =""

#block code to make every alternate word

for i in range(0, len(user_word_split_2)): #loop to make every second letter upper

    if i % 2 == 0:
        words_sep = words_sep + " "+ user_word_split_2[i].lower() 

    else:
        words_sep = words_sep +" " + user_word_split_2[i].upper() 
    

#Block code to join the individual characters
final_string_2 = "".join(words_sep)

#Block code to product the final results
print(final_string_2)
Answered By: eli_257
s = "Here is my dog"

words = s.split()
words[1::2] = map(str.upper, words[1::2])
s = " ".join(words)

print(s)

Attempt This Online!

Answered By: Kelly Bundy
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.