Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading