+ 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.
7 Réponses
+ 2
How is a word qualified as odd or even?
+ 1
Such as in a sentence the first word would be odd, second word would be even, etc. like that
+ 1
split by spaces and then take a certain action if the index is odd or even.
0
thanks, for reversing the even words in the string, would i create a new for loop?
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)
0
check it again, I missed that part originally. fixed it
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())))