如何反转字符串中的每个单词,并将python中每个单词的第一个字母大写?

2024-06-16 10:13:59 发布

您现在位置:Python中文网/ 问答频道 /正文

如何反转字符串中的每个单词,并将python中每个单词的第一个字母大写

input = 'this is the best'
output = Siht Si Eht Tseb

Tags: the字符串inputoutputis字母this单词
3条回答

只要做:

" ".join([str(i[::-1]).title() for i in input.split()])

使用^{},然后反转字符串,最后使用^{}

s = 'this is the best'

res = " ".join([si[::-1].capitalize() for si in s.split()])
print(res)

输出

Siht Si Eht Tseb

这里的其他答案也适用。但我认为这会更容易理解

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)

相关问题 更多 >