Home > Mobile >  How to reverse each word in string and first letter is capitalize of each word in python?
How to reverse each word in string and first letter is capitalize of each word in python?

Time:10-19

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

CodePudding user response:

Use split, 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

CodePudding user response:

Just do:

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

CodePudding user response:

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)

CodePudding user response:

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
  • Related