Home > OS >  how to reverse a string in python without changing the position of words?
how to reverse a string in python without changing the position of words?

Time:03-13

str5 = 'peter piper picked a peck of pickled peppers.'
b = str5.split()
for i in b:
    print(i[::-1])

#output:

retep
repip
dekcip
a
kcep
fo
delkcip
.sreppep

what should I do to make it look like in one single line?

CodePudding user response:

Just create a new empty str variable and concatenate it.

str5 = 'peter piper picked a peck of pickled peppers.'
b = str5.split()
rev_str5 = ""
for i in b:
    rev_str5 = rev_str5   ' '   i[::-1]
print(rev_str5.lstrip()) # Removes the one space in the starting.

Here's a shorter method too. Thanks for the comment:

str5 = 'peter piper picked a peck of pickled peppers.'    
print(' '.join(w[::-1] for w in str5.split()))

Output:

retep repip dekcip a kcep fo delkcip .sreppep

CodePudding user response:

I like something pythonic like

phrase = "peter piper picked a peck of pickled peppers."
reversed_word_list = [word[::-1] for word in phrase.split()]
reversed_phrase = " ".join(reversed_word_list)
  • Related