How to reverse each word in string and first letter is capitalize of each word in python?
input = 'this is the best'
output = Siht Si Eht Tseb
Usesplit
, then reverse the string and finally capitalize
:
s = 'this is the best'
res = " ".join([si[::-1].capitalize() for si in s.split()])
print(res)
Output
Siht Si Eht Tseb
做就是了:
" ".join([str(i[::-1]).title() for i in input.split()])
The other answers here works aswell. But I think this will be a lot easier to understand.
s = 'this is the best'
words = s.split() # Split into list of each word
res = ''
for word in words:
word = word[::-1] # Reverse the word
word = word.capitalize() + ' ' # Capitalize and add empt space
res += word # Append the word to the output-string
print(res)
input=' '.join(w[::-1] for w in input.split()) #reverse each word
input=' '.join(w[0].upper()+w[1:] for w in input.split()) #capitalise 1st letter
Output
Siht Si Eht Tseb
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.