How to reverse a string in python ?

Active September 22, 2021    /    Viewed 298    /    Comments 0    /    Edit


Examples of how to reverse a string in python

Create a string in python

Let's create a simple string using python:

s = 'abcdef'

print(s)

gives

abcdef

Note that

type(s)

gives

str

Reverse a string in python

Example 1

A straightforward solution to reverse a string in python is to do

s1 = s[::-1]

print(s1)

gives

fedcba

Example 2

Another example

s2 = "".join(reversed(s))

print(s2)

gives

fedcba

Example 3

Similar as example 2 but decomposed in several steps:

Step 1: convert the string into a list:

s_as_list = list(s)

Step 2: reverse the list

s_as_list.reverse()

Step 3: Concatenate the list into a string

s3 = "".join(s_as_list)

print(s3)

gives

fedcba

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!