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
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))
+ 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 )
+ 3
Entering "this is an attempt" will output "siht si na ATTEMPT": isn't it what is expected?
+ 3
So all the words don't be uppercase, only odd words, and even words are reversed... or should I miss something?
0
this is pretty easy man
0
yeah I am having trouble computing it
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
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
0
entering "My name is python" should give MY eman IS nohtyp.
0
The odd words in a sentence should be capitalized and even words will be reversed
0
yeah that is right
0
Thanks a lot man, it is a homework due for my class and you saved the day