Examples of how to reverse a string in python
Table of contents
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