Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

+2 votes
3 views
by (3.9k points)

How can I reverse a str object in Python?

2 Answers

0 votes
by (46k points)
edited by

The fastest approach to do this is using s[::-1] , You can also try ''.join(reversed(s)) it's comparatively more readable but three times slower. Ex.

>>> 'q string'[::-1]
'gnirts q'

 >>> ''.join(reversed('q string'))

'gnirts q'


Hope this helps. Cheers.....!! 

0 votes
by (106k points)

Python gives us a very easy way to reverse our string:-

We can reverse our string by using Extended Slice method:-

Extended Slice:-

This slicing method works by doing [begin: end: step] leaving begin and end off and specifying a step of -1, it reverses a string.

Example:-

string= "hello world"

string[::-1]

 

image

Related questions

0 votes
1 answer
asked Jan 2, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
asked Jul 9, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)
0 votes
4 answers
0 votes
1 answer
asked Apr 9, 2021 in Java by sheela_singh (9.5k points)

Browse Categories

...