0

Creating a python program where odd words are upper cased and even words are reversed in a string

The program should generate a string where the odd words are upper cased and even words are reversed

28th Apr 2017, 8:10 PM
Sharar Wassey
12 Respuestas
+ 4
sentence = input("Enter your sentence: "); words = sentence.split(); newstr = [] for w in words: if (len(w) % 2) == 0: newstr.append(w[::-1]) else: newstr.append(w.upper()) print(" ".join(newstr))
29th Apr 2017, 1:34 AM
visph
visph - avatar
+ 4
Oh, I finally get my missunderstood: I assumed that odd words where words with odd length, and same way for "even words"... Code fixed: sentence = input("Enter your sentence: "); words = sentence.split(); newstr = [] for w in range(len(words)): if (w % 2) != 0: newstr.append(words[w][::-1]) else: newstr.append(words[w].upper()) print(" ".join(newstr)) [ edit ] Change condition between == and !=, to inverse the rules ( as first element should be consider numbered zero or one, make it even or odd :P )
29th Apr 2017, 2:29 AM
visph
visph - avatar
+ 3
Entering "this is an attempt" will output "siht si na ATTEMPT": isn't it what is expected?
29th Apr 2017, 2:13 AM
visph
visph - avatar
+ 3
So all the words don't be uppercase, only odd words, and even words are reversed... or should I miss something?
29th Apr 2017, 2:19 AM
visph
visph - avatar
0
this is pretty easy man
28th Apr 2017, 11:47 PM
Giannis Tsirovasilis
Giannis Tsirovasilis - avatar
0
yeah I am having trouble computing it
28th Apr 2017, 11:48 PM
Sharar Wassey
0
sorry thought you were asking it as a challenge. let str be the name of your string variable then if (len(str) % 2 == 0) str = str[::-1] else str = str.upper() check if this works
29th Apr 2017, 12:32 AM
Giannis Tsirovasilis
Giannis Tsirovasilis - avatar
0
Visph, your code almost works except that all the words are upper case and not the odd ones. The even words are also not reversed
29th Apr 2017, 2:07 AM
Sharar Wassey
0
entering "My name is python" should give MY eman IS nohtyp.
29th Apr 2017, 2:15 AM
Sharar Wassey
0
The odd words in a sentence should be capitalized and even words will be reversed
29th Apr 2017, 2:18 AM
Sharar Wassey
0
yeah that is right
29th Apr 2017, 2:20 AM
Sharar Wassey
0
Thanks a lot man, it is a homework due for my class and you saved the day
29th Apr 2017, 2:34 AM
Sharar Wassey