如何在Python中反转字符串中的每个单词并且每个单词的第一个字母大写?
input = 'this is the best'
output = Siht Si Eht Tseb
使用split
,然后反转字符串,最后使用capitalize
:
s = 'this is the best'
res = " ".join([si[::-1].capitalize() for si in s.split()])
print(res)
Siht Si Eht Tseb
Just do:
" ".join([str(i[::-1]).title() for i in input.split()])
这里的其他答案也适用。但我认为这样更容易理解。
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 empty space
res += word # Append the word to the output string
print(res)