+2 votes
2 views
by (3.9k points)

How can I reverse a str object in Python?

2 Answers

0 votes
by (46.1k 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 (107k 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

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


Categories

...