Reverse a string (by slicing with negative step) - Python

Here is an example to reverse a string by slicing with -1 step.

a = 'abcde'

b = a[::-1]

print(b)  # edcba

A string is a kind of list and we can choose elements on some conditions using Python slicing. The expression ::-1 selecting all the elements with reversed order. An empty string is reversed to itself.

a = ''

b = a[::-1]

print(b)  #

Python slicing is the general way to reverse items of an iterable. It uses two semicolons and three parameters each of which can be omitted. Slicing parameters are the start, end and step. In this case, the start and end are omitted so the start is 0 and the end is the last position.

Use of reversed() and join()

s = reversed('Python')

print(s)  # <reversed object at 0x10ebc5610>
print(type(s))  # <class 'reversed'>

for i in s:
    print(i)

# n
# o
# h
# t
# y
# P

You can reverse a string using the reversed(), a Python built-in function, that returns the reversed object. After making the reversed object, use the join() to concatenate all the letters of it.

s = reversed('Python')
a = ''.join(s)

print(a)  # nohtyP

This way is also simple and can be written in one line. But it may be better to use Python slicing than the reversed() if you are not used to the slicing with a negative step.

Examples of reversing strings

a = 'computer'[::-1]
b = 'world'[::-1]
c = '1234'[::-1]
d = '@"#'[::-1]

print(a)  # retupmoc
print(b)  # dlrow
print(c)  # 4321
print(d)  # #"@

Note: Python slicing syntax

Slicing with -1 step is used to reverse a string, list, range, tuple, etc.

a1 = [1, 2, 3, 4]
a2 = range(7)
a3 = ('x', 'y', 'z')

b1 = a1[::-1]
b2 = a2[::-1]
b3 = a3[::-1]

print(b1)  # [4, 3, 2, 1]
print(b2)  # range(6, -1, -1)
print(b3)  # ('z', 'y', 'x')

for i in b2:
    print(i)

# 6
# 5
# 4
# 3
# 2
# 1
# 0

Python String

Python Tutorial