Question about capitalize and reverse string. | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

Question about capitalize and reverse string.

how would you capitalize odd words in a string and reverse the even words in a string? Thanks.

26th Apr 2017, 1:13 AM
Raad Wassey
7 Réponses
+ 2
How is a word qualified as odd or even?
26th Apr 2017, 1:20 AM
Bebida Roja
Bebida Roja - avatar
+ 1
Such as in a sentence the first word would be odd, second word would be even, etc. like that
26th Apr 2017, 1:22 AM
Raad Wassey
+ 1
split by spaces and then take a certain action if the index is odd or even.
26th Apr 2017, 1:24 AM
Bebida Roja
Bebida Roja - avatar
0
thanks, for reversing the even words in the string, would i create a new for loop?
26th Apr 2017, 1:38 AM
Raad Wassey
0
myString="This is a string example" myList=myString.split(" ") myString="" for i in range(len(myList)): up=myList[i].upper() rev=myList[i][::-1] if i%2==0: myString=myString+up+" " else: myString=myString+rev+" " print(myString)
26th Apr 2017, 1:38 AM
LordHill
LordHill - avatar
0
check it again, I missed that part originally. fixed it
26th Apr 2017, 1:39 AM
LordHill
LordHill - avatar
0
# you could also use a generator comprehension test = 'here is a string' print(' '.join(x[::-1]if ind%2 else x.upper() for ind,x in enumerate(test.split())))
26th Apr 2017, 11:50 AM
richard