Как написать слово задом наперед python

Обзор трех основных способов перевернуть строку Python. Также известная как «срез», обратная итерация и классический алгоритм переворота на месте. Также вы увидите показатели производительности выполняемого кода.

Какой лучший способ перевернуть строки Python? Разумеется, переворот строк не используется так часто в повседневном программировании, однако это нередкий вопрос во время интервью:

# У вас есть:

‘TURBO’

# Нужно сделать из него:

‘OBRUT’

Одна из вариаций этого вопроса — это написать функцию, которая проверяет, является ли заданная строка палиндромом, т.е., читается ли она одинаково в правильном и в обратном порядке:

def is_palindrome(string):

    reversed_string = string[::1]

    return string == reversed_string

print(is_palindrome(‘TACOCAT’)) # True

print(is_palindrome(‘TURBO’)) # False

Очевидно, нам нужно выяснить, как перевернуть строку для реализации функции is_palindrome в Python… как это сделать?

Объекты строк str в Python содержат не встроенный метод .reverse(), как вы можете предположить, если вы пришли в Python из другого языка программирования, такой как Java или C#, следующий подход будет неверным:

>>> ‘TURBO’.reverse()

Traceback (most recent call last):

  File «<stdin>», line 1, in <module>

AttributeError: ‘str’ object has no attribute ‘reverse’

В данном руководстве мы изучим три основных способа перевернуть строку в Python:

Строки следуют протоколу последовательности Python. И все последовательности поддерживают любопытную функцию под названием срез. Вы можете смотреть на срез как на расширение синтаксиса индексирования квадратных скобок.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Это включает в себя отдельный случай, где срез последовательности с “[::-1]” создает перевернутую копию. Так как строки Python являются последовательностями, это быстрый и простой способ получить отраженную копию строки:

text = ‘TURBO’[::1]

print(text) # ‘OBRUT’

Конечно, вы можете вставить срез в функцию, чтобы сделать более очевидным то, что делает код:

def reverse_string1(s):

    return s[::1]

print(reverse_string1(‘TURBO’)) # ‘OBRUT’

Как вам такое решение?

Это быстро и удобно. Но, на мой взгляд, главный недостаток переворота строки при помощи среза заключается в том, что он использует продвинутую возможность Python, которую многие разработчики могут назвать «тайной и древней».

Я не виню их — срез списка может быть трудным для понимания, особенно если вы впервые сталкиваетесь с этим непонятным лаконичным синтаксисом.

Когда я читаю код Python, в котором используется срез, мне, как правило, приходиться задерживаться и фокусироваться, чтобы мысленно разобрать утверждение, чтобы убедиться в том, что я правильно понимаю происходящее.

Самой большой проблемой для меня является то, что синтаксис среза “[::-1]” недостаточно явно информирует о том, что он создает отраженную копию оригинальной строки.

По этой причине я думаю, что использование функцию среза в Python для переворота строки — достойное решение, но это может быть сложно для чтения неподготовленному человеку.

Двигаемся дальше…

Перевернуть сроку при помощи reversed() и str.join()

Переворот строки с обратной итерацией при помощи встроенной функции reversed() — еще один способ сделать это. Вы получаете обратный итератор, который можно использовать цикличного перемещения элементов строки в обратном порядке:

for elem in reversed(‘TURBO’):

    print(elem)

Результат:

Использование reversed() не модифицирует оригинальную строку (что не сработало бы в любом случае, так как строки неизменны в Python). Происходит следующее: вы получаете «вид» существующей строки, который вы можете использовать для обзора всех элементов в обратном порядке.

Это сильная техника, которая использует преимущество протокола итерации Python.

Итак, все что вы видели — это способы итерации над символами строки в обратном порядке. Но как использовать эту технику для создания отраженной копии строки Python при помощи функции reversed()?

Сделаем это вот так:

text = ».join(reversed(‘TURBO’))

print(text) # ‘OBRUT’

В этом фрагменте кода используется метод .join(), объединяющий все символы, полученные в результате обратной итерации в новой строке. Хитро и удобно!

Конечно, вы можете еще раз извлечь этот код в отдельную функцию для создания надлежащей функции «перевернутой строки» в Python. Вот так:

def reverse_string2(s):

    return «».join(reversed(s))

data = reverse_string2(‘TURBO’)

print(data) # ‘OBRUT’

Мне действительно нравится этот подход обратного итератора для переворота строк в Python.

Он четко сообщает о том, что происходит, и даже новичок в языке на интуитивном уровне может понять, что я создаю перевернутую копию оригинальной строки.

И хотя понимание работы итераторов на глубоком уровне — полезно и похвально, это не абсолютная необходимость для использования этой техники.

«Классический» алгоритм переворота строк Python

Это классический алгоритм переворачивания строк из учебников, портированный для Python. Так как строки Python являются неизменными, вам для начала нужно конвертировать вводимую строку в меняемый список символов, таким образом вы сможете выполнить смену символов на месте:

def reverse_string3(s):

    chars = list(s)

    for i in range(len(s) // 2):

        tmp = chars[i]

        chars[i] = chars[len(s) i 1]

        chars[len(s) i 1] = tmp

    return ».join(chars)

data = reverse_string3(‘TURBO’)

print(data) # ‘OBRUT’

Как вы видите, это решение не то чтобы родное для Python, и не то, чтобы идиоматическое. Здесь не используются возможности Python и вообще, это явный порт алгоритма из языка программирования C.

И если этого не достаточно — это самое медленное решение, как вы увидите в следующем разделе, я буду проводить бенчмаркинг по всем трем реализациям.

Сравнение производительности

После реализации всех трех подходов к переворачиванию строк, показанных в этом руководстве, мне стало любопытна их относительная производительность.

Так что я провел небольшой бенчмаркинг:

>>> import timeit

>>> s = ‘abcdefghijklmnopqrstuvwxyz’ * 10

>>> timeit.repeat(lambda: reverse_string1(s))

[0.6848115339962533, 0.7366074129968183, 0.7358982900041156]

>>> timeit.repeat(lambda: reverse_string2(s))

[5.514941683999496, 5.339547180992668, 5.319950777004124]

>>> timeit.repeat(lambda: reverse_string3(s))

[48.74324739299482, 48.637329410004895, 49.223478018000606]

Хорошо, это интересно… вот результаты в форме таблицы:

Перевернуть строку в Python

Как вы видите, есть огромная разница в производительности между этими тремя реализациями.

Срез — самый быстрый подход, reversed() медленнее среза в 8 раз, и «классический» алгоритм медленнее в 71 раз в этой проверке!

Теперь, смену символов на месте определенно можно оптимизировать (сообщите в комментариях внизу о вашем решении по улучшению, если хотите) — однако это сравнение производительности дает нам явное представление о том, какая операция отражения является самой быстрой в Python.

Итог: Переворачивания строк в Python

Переворачивание строк — это стандартная операция в программировании (и во время интервью). В этом руководстве вы узнали о трех разных подходах к переворачиванию строк в Python.

Давайте проведем краткий обзор каждого из способов, перед тем как я дам рекомендации о каждом варианте:

Вариант 1: срез списка [::-1]

Вы можете использовать синтаксис среза Python для создания перевернутой копии строки. Это хорошо работает, однако синтаксис может быть непонятным для пользователей Python.

print(‘TURBO’[::1]) # ‘OBRUT’

  • Создает переверную копию строки;
  • Это самый быстрый способ переворота строки в Python

Вариант 2: reversed() and str.join()

Встроенная функция reversed() позволяет вам создать отраженный итератор строки Python (или любой другой последовательный объект). Это гибкое и простое решение, которое использует определенные продвинутые функции Python, но при этом остается читаемым благодаря четкому названию reversed()

print(».join(reversed(‘TURBO’))) # ‘OBRUT’

  • Функция reversed() возвращает итератор, который проводит итерацию над символами в строке в обратном порядке
  • Этот поток символов необходимо комбинировать в строку при помощи функции str.join()
  • Этот способ медленнее среза, но более читаемый.

Вариант 3: «Крутите сами»

Использование стандартного алгоритма замены символов с предварительным портированием в Python работает, но сопровождается вялой производительностью и читаемостью, в сравнении с другими способами.

def reverse_string(s):

    chars = list(s)

    for i in range(len(s) // 2):

        tmp = chars[i]

        chars[i] = chars[len(s) i 1]

        chars[len(s) i 1] = tmp

    return ».join(chars)

data = reverse_string(‘TURBO’)

print(data) # ‘OBRUT’

  • Это намного медленнее среза и обратной итерации (в зависимости от реализации);
  • Данный алгоритм не рекомендуется, только если вы не в ситуации с интервью.

Если вы думаете о том, какой из способов подходит для переворачивания строки лучше всего, мой ответ: «В зависимости от ситуации». Лично я предпочитаю подход с использованием функции reversed(), так как она объясняет саму себя и по понятным причинам быстрая.

Однако, также присутствует аргумент, где наш подход среза является в 8 раз быстрее, что может быть предпочтительно, если есть необходимость в производительности.

В зависимости от вашего случая, это может быть грамотным решением. Кроме этого, это весьма уместная ситуация для цитаты Дональда Кнута:

Программисты тратят огромное количество времени думая, или переживая о скорости некритичных частей программ, и эти попытки увеличения эффективности на самом деле оказывают сильное негативное воздействие при отладке и обслуживании.

Мы должны забыть о существовании несущественной эффективности, скажем, в 97% случаев: преждевременная оптимизация — корень зла.

Однако мы должны прилагать все усилия в этих критических 3%.»

Дональд Кнут

По этой причине, я бы не стал беспокоиться о производительности переворачивания строк в ваших программах, только если это не интегральная часть того, что делает ваш софт. Если вы отражаете миллионы строк в узком цикле, любой ценой оптимизируйте скорость.

Но для обычного приложения Python это не даст существенной разницы. Так что я выбираю наиболее читаемым (и следовательно, поддерживаемым) подходом.

В моем случае это вариант 2: reversed() + join().

Если вы хотите углубиться в вопрос, вы можете найти море информации в документации и интернете. Кстати, комментарии в разделе ниже приветствуются! Поделитесь с нами вашими любимыми техниками отражения строк.

Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.

E-mail: vasile.buldumac@ati.utm.md

Образование
Universitatea Tehnică a Moldovei (utm.md)

  • 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
  • 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»

1. Использование цикла со строкой в результате

Создадим функцию reversed1 с аргументом variable, где variable — переменная, хранящая строку, которую мы хотим перевернуть. Так как строка являются неизменяемым объектом, то создадим отдельную, пока что пустую переменную res, которая в будущем будет хранить результат.

def reversed1(variable):
    res=''

В функцию поместим цикл, который будет «прохаживаться» по каждому из элементов строки. Начнем мы с конца строки, используя положительные индексы, соответственно параметр start функции range —len(variable)-1. -1 потому, что длина строки всегда на 1 больше, чем индекс последнего ее элемента. Закончить мы должны на первом символе строки, поэтому параметр stop функции range() — -1, поскольку перечисляются числа до значения этого параметра, не включительно. Параметр step — -1, потому что мы считаем в обратном порядке.

def reversed1(variable):
    res=''
    for i in range(len(variable)-1,-1,-1):
        pass

Теперь заполним тело цикла — проведем конкатенацию между старым значением res и элементом строки с индексом i. Таким образом, при каждой итерации цикла мы добавляем по одному символу к результату. После окончания цикла вернем результат.

Полный код:

def reversed1(variable):
    res=''
    for i in range(len(variable)-1,-1,-1):
        res+=variable[i]
    return res

n = reversed1(input())
print(n)

2. Использование цикла со списком в результате

Этот способ аналогичен предыдущему, единственное его отличие заключается в типе данных переменной res — здесь она является списком.

Вместо конкатенации можно использовать метод append(), с помощью которого мы добавляем элемент, указанный в качестве аргумента к методу, в конец списка. Итак, мы получили:

def reversed2(variable):
    res=[]
    for i in range(len(variable)-1,-1,-1):
        res.append(variable[i])
    return res

Функция пока что возвращает список, состоящий из односимвольных элементов. Если нас это не устраивает, то почему бы не преобразовать список в строку при помощи метода join()? Сделаем это, добавив конструкцию res=''.join(res).

Полный код:

def reversed1(variable):
    res=[]
    for i in range(len(variable)-1,-1,-1):
        res.append(variable[i])
    res=''.join(res)
    return res

n = reversed1(input())
print(n)

3. Рекурсия

Третий в нашем обзоре способ — рекурсия, как всегда трудная для понимания. Как всегда создаем функцию, но не спешим помещать туда цикл.

Начну объяснение с конца. Если мы записали в результат все символы кроме первого, то длина оставшейся строки равна единице и, следовательно, ее нужно вернуть. Получаем:

def reversed3(variable): 
    if len(variable) == 1:
        return variable

Но если длина строки больше одного, то нужно вернуть последний из ее элементов и вызвать эту же функцию, но уже отрезав последний символ. Сделать это мы можем с помощью среза variable[:-1]. Обновим картину:

def reversed3(variable): 
    if len(variable) == 1:
        return variable
    else:
        return variable[-1] + reversed3(variable[:-1])

Использование else:здесь необязательно, так как после возвращения чего-либо этой функцией она завершится. Поэтому конструкцию return variable[-1] + reverse3(variable[:-1]) можно поместить напрямую в тело функции. Конечный вариант решения:

def reversed3(variable): 
    if len(variable) == 1:
        return variable
    return variable[-1] + reversed3(variable[:-1])

n = reversed3(input())
print(n)

4. Использование встроенной функции

В Python 3 встроена специальная функция reversed(), в качестве аргумента она принимает список или строку, а возвращает итератор последовательности значений, состоящей из всех элементов аргумента в обратном порядке.

Простыми словами — недостаточно написать res = reversed(variable), данные нужно преобразовать в нужный тип (в нашем случае — в строку). Сделать мы это можем при помощи метода join(), соединив последовательность через пустую строку. После выполненных действий возвращаем результат. Код:

def reversed4(variable):
    res=''.join(reversed(variable))
    return res

n = reversed4(input())
print(n)

5. Срез строки

Можете представить способ перевернуть строку, который был бы короче названия функции? А я могу!

Срез строки — вещь прекрасная, но порой пугающая новичков «уплотненным» синтаксисом. Срез содержит три параметра — [start:stop:step], аналогично функции range(). Подробнее о них вы можете прочитать в других статьях на Хабре.

Для способа с использованием срезов не нужно даже создавать функцию, только зря строки и время потратите. Все элементарно — присвоим параметру step значение -1 и пропустим два других параметра, происходит магия — строка переворачивается:

n = input()[::-1]
print(n)

Ввод:qwerty

Вывод: ytrewq

Конечно, никакой магии здесь нет, мы просто перебираем символы с шагом -1, то есть в обратном порядке.

Заключение

Первый и второй способы как нельзя лучше подходят, если во время переворота строки нужно ее изменять. При этом они значительно уступают 4 и 5 способам в скорости. Читаются умеренно хорошо, поэтому в некоторых случаях их уместно использовать.

Насчет третьего способа много сказать не могу, поскольку не могу придумать ему применение. Такой способ плохо читается и довольно медленный, поэтому я не рекомендую его использовать.

Четвертый способ довольно быстрый, отлично читается и подходит во многих случаях.

Пятый способ — самый быстрый, хорошо читается, очень краткий (6 символов), поэтому его я считаю наиболее предпочтительным.

Сравнительную таблицу скорости некоторых способов вы можете найти по ссылке — https://python-scripts.com/reversed

Если знаете что-либо еще по этой теме, хотите меня поправить или дать идею — пишите в комментариях, я все прочту и приму к сведению. Удачи!

This answer is a bit longer and contains 3 sections: Benchmarks of existing solutions, why most solutions here are wrong, my solution.

The existing answers are only correct if Unicode Modifiers / grapheme clusters are ignored. I’ll deal with that later, but first have a look at the speed of some reversal algorithms:

enter image description here

NOTE: I’ve what I called list_comprehension should be called slicing

list_comprehension  : min:   0.6μs, mean:   0.6μs, max:    2.2μs
reverse_func        : min:   1.9μs, mean:   2.0μs, max:    7.9μs
reverse_reduce      : min:   5.7μs, mean:   5.9μs, max:   10.2μs
reverse_loop        : min:   3.0μs, mean:   3.1μs, max:    6.8μs

enter image description here

list_comprehension  : min:   4.2μs, mean:   4.5μs, max:   31.7μs
reverse_func        : min:  75.4μs, mean:  76.6μs, max:  109.5μs
reverse_reduce      : min: 749.2μs, mean: 882.4μs, max: 2310.4μs
reverse_loop        : min: 469.7μs, mean: 577.2μs, max: 1227.6μs

You can see that the time for the list comprehension (reversed = string[::-1]) is in all cases by far the lowest (even after fixing my typo).

String Reversal

If you really want to reverse a string in the common sense, it is WAY more complicated. For example, take the following string (brown finger pointing left, yellow finger pointing up). Those are two graphemes, but 3 unicode code points. The additional one is a skin modifier.

example = "👈🏾👆"

But if you reverse it with any of the given methods, you get brown finger pointing up, yellow finger pointing left. The reason for this is that the «brown» color modifier is still in the middle and gets applied to whatever is before it. So we have

  • U: finger pointing up
  • M: brown modifier
  • L: finger pointing left

and

original: LMU                    👈🏾👆
reversed: UML (above solutions)  ☝🏾👈
reversed: ULM (correct reversal) 👆👈🏾

Unicode Grapheme Clusters are a bit more complicated than just modifier code points. Luckily, there is a library for handling graphemes:

>>> import grapheme
>>> g = grapheme.graphemes("👈🏾👆")
>>> list(g)
['👈🏾', '👆']

and hence the correct answer would be

def reverse_graphemes(string):
    g = list(grapheme.graphemes(string))
    return ''.join(g[::-1])

which also is by far the slowest:

list_comprehension  : min:    0.5μs, mean:    0.5μs, max:    2.1μs
reverse_func        : min:   68.9μs, mean:   70.3μs, max:  111.4μs
reverse_reduce      : min:  742.7μs, mean:  810.1μs, max: 1821.9μs
reverse_loop        : min:  513.7μs, mean:  552.6μs, max: 1125.8μs
reverse_graphemes   : min: 3882.4μs, mean: 4130.9μs, max: 6416.2μs

The Code

#!/usr/bin/env python3

import numpy as np
import random
import timeit
from functools import reduce
random.seed(0)


def main():
    longstring = ''.join(random.choices("ABCDEFGHIJKLM", k=2000))
    functions = [(list_comprehension, 'list_comprehension', longstring),
                 (reverse_func, 'reverse_func', longstring),
                 (reverse_reduce, 'reverse_reduce', longstring),
                 (reverse_loop, 'reverse_loop', longstring)
                 ]
    duration_list = {}
    for func, name, params in functions:
        durations = timeit.repeat(lambda: func(params), repeat=100, number=3)
        duration_list[name] = list(np.array(durations) * 1000)
        print('{func:<20}: '
              'min: {min:5.1f}μs, mean: {mean:5.1f}μs, max: {max:6.1f}μs'
              .format(func=name,
                      min=min(durations) * 10**6,
                      mean=np.mean(durations) * 10**6,
                      max=max(durations) * 10**6,
                      ))
        create_boxplot('Reversing a string of length {}'.format(len(longstring)),
                       duration_list)


def list_comprehension(string):
    return string[::-1]


def reverse_func(string):
    return ''.join(reversed(string))


def reverse_reduce(string):
    return reduce(lambda x, y: y + x, string)


def reverse_loop(string):
    reversed_str = ""
    for i in string:
        reversed_str = i + reversed_str
    return reversed_str


def create_boxplot(title, duration_list, showfliers=False):
    import seaborn as sns
    import matplotlib.pyplot as plt
    import operator
    plt.figure(num=None, figsize=(8, 4), dpi=300,
               facecolor='w', edgecolor='k')
    sns.set(style="whitegrid")
    sorted_keys, sorted_vals = zip(*sorted(duration_list.items(),
                                           key=operator.itemgetter(1)))
    flierprops = dict(markerfacecolor='0.75', markersize=1,
                      linestyle='none')
    ax = sns.boxplot(data=sorted_vals, width=.3, orient='h',
                     flierprops=flierprops,
                     showfliers=showfliers)
    ax.set(xlabel="Time in ms", ylabel="")
    plt.yticks(plt.yticks()[0], sorted_keys)
    ax.set_title(title)
    plt.tight_layout()
    plt.savefig("output-string.png")


if __name__ == '__main__':
    main()

Python string library doesn’t support the in-built “reverse()” as done by other python containers like list, hence knowing other methods to reverse string can prove to be useful. This article discusses several ways to achieve it in Python. 

Example:

Input:  Geeksforgeeks
Output: skeegrofskeeG

Reverse a string in Python using a loop

In this example, we call a function to reverse a string, which iterates to every element and intelligently joins each character in the beginning so as to obtain the reversed string. 

Time complexity: O(n) 
Auxiliary Space: O(1) 

Implementation:

Python3

def reverse(s):

    str = ""

    for i in s:

        str = i + str

    return str

s = "Geeksforgeeks"

print("The original string is : ", end="")

print(s)

print("The reversed string(using loops) is : ", end="")

print(reverse(s))

Output

The original string is : Geeksforgeeks
The reversed string(using loops) is : skeegrofskeeG

Reverse a string in Python using recursion

The string is passed as an argument to a recursive function to reverse the string. In the function, the base condition is that if the length of the string is equal to 0, the string is returned. If not equal to 0, the reverse function is recursively called to slice the part of the string except the first character and concatenate the first character to the end of the sliced string. ‘

Implementation:

Python3

def reverse(s):

    if len(s) == 0:

        return s

    else:

        return reverse(s[1:]) + s[0]

s = "Geeksforgeeks"

print("The original string is : ", end="")

print(s)

print("The reversed string(using recursion) is : ", end="")

print(reverse(s))

Output

The original string is : Geeksforgeeks
The reversed string(using recursion) is : skeegrofskeeG

Time complexity: O(n), for recursion to reverse 
Auxiliary Space: O(n), for recursion call stack

Reverse string in Python using stack

An empty stack is created. One by one character of the string is pushed to the stack. One by one all characters from the stack are popped and put back to a string. 

Time complexity: O(n) 
Auxiliary Space: O(n) 

Implementation:

Python3

def createStack():

    stack = []

    return stack

def size(stack):

    return len(stack)

def isEmpty(stack):

    if size(stack) == 0:

        return true

def push(stack, item):

    stack.append(item)

def pop(stack):

    if isEmpty(stack):

        return

    return stack.pop()

def reverse(string):

    n = len(string)

    stack = createStack()

    for i in range(0, n, 1):

        push(stack, string[i])

    string = ""

    for i in range(0, n, 1):

        string += pop(stack)

    return string

s = "Geeksforgeeks"

print("The original string is : ", end="")

print(s)

print("The reversed string(using stack) is : ", end="")

print(reverse(s))

Output

The original string is : Geeksforgeeks
The reversed string(using stack) is : skeegrofskeeG

Reverse string in Python using an extended slice

Extended slice offers to put a “step” field as [start, stop, step], and giving no field as start and stop indicates default to 0 and string length respectively, and “-1” denotes starting from the end and stop at the start, hence reversing a string. 

Time complexity: O(n) 
Auxiliary Space: O(1) 

Implementation:

Python3

def reverse(string):

    string = string[::-1]

    return string

s = "Geeksforgeeks"

print("The original string is : ", end="")

print(s)

print("The reversed string(using extended slice syntax) is : ", end="")

print(reverse(s))

Output

The original string is : Geeksforgeeks
The reversed string(using extended slice syntax) is : skeegrofskeeG

Reverse string in Python using reversed() method

The reversed() returns the reversed iterator of the given string and then its elements are joined empty string separated using join(). And reversed order string is formed. 

Time complexity: O(n) 
Auxiliary Space: O(n) 

Implementation:

Python3

def reverse(string):

    string = "".join(reversed(string))

    return string

s = "Geeksforgeeks"

print("The original string is : ", end="")

print(s)

print("The reversed string(using reversed) is : ", end="")

print(reverse(s))

Output

The original string is : Geeksforgeeks
The reversed string(using reversed) is : skeegrofskeeG

Reverse string in Python using list comprehension()

List comprehension creates the list of elements of a string in reverse order and then its elements are joined using join(). And reversed order string is formed.

Time complexity: O(n)
Auxiliary Space: O(1) 

Implementation:

Python3

def reverse(string):

    string = [string[i] for i in range(len(string)-1, -1, -1)]

    return "".join(string)

s = "Geeksforgeeks"

print("The original string  is : ", s)

print("The reversed string(using reversed) is : ", reverse(s))

Output

The original string  is :  Geeksforgeeks
The reversed string(using reversed) is :  skeegrofskeeG

Reverse string in Python using the function call

Function to reverse a string by converting string to list then reversed it and again convert it to string.

Time complexity: O(n)
Auxiliary Space: O(1) 

Implementation:

Python3

def reverse(string):

    string = list(string)

    string.reverse()

    return "".join(string)

s = "Geeksforgeeks"

print("The original string  is : ", s)

print("The reversed string(using reversed) is : ", reverse(s))

Output

The original string  is :  Geeksforgeeks
The reversed string(using reversed) is :  skeegrofskeeG

When you’re using Python strings often in your code, you may face the need to work with them in reverse order. Python includes a few handy tools and techniques that can help you out in these situations. With them, you’ll be able to build reversed copies of existing strings quickly and efficiently.

Knowing about these tools and techniques for reversing strings in Python will help you improve your proficiency as a Python developer.

In this tutorial, you’ll learn how to:

  • Quickly build reversed strings through slicing
  • Create reversed copies of existing strings using reversed() and .join()
  • Use iteration and recursion to reverse existing strings manually
  • Perform reverse iteration over your strings
  • Sort your strings in reverse order using sorted()

To make the most out of this tutorial, you should know the basics of strings, for and while loops, and recursion.

Reversing Strings With Core Python Tools

Working with Python strings in reverse order can be a requirement in some particular situations. For example, say you have a string "ABCDEF" and you want a fast way to reverse it to get "FEDCBA". What Python tools can you use to help?

Strings are immutable in Python, so reversing a given string in place isn’t possible. You’ll need to create reversed copies of your target strings to meet the requirement.

Python provides two straightforward ways to reverse strings. Since strings are sequences, they’re indexable, sliceable, and iterable. These features allow you to use slicing to directly generate a copy of a given string in reverse order. The second option is to use the built-in function reversed() to create an iterator that yields the characters of an input string in reverse order.

Reversing Strings Through Slicing

Slicing is a useful technique that allows you to extract items from a given sequence using different combinations of integer indices known as offsets. When it comes to slicing strings, these offsets define the index of the first character in the slicing, the index of the character that stops the slicing, and a value that defines how many characters you want to jump through in each iteration.

To slice a string, you can use the following syntax:

a_string[start:stop:step]

Your offsets are start, stop, and step. This expression extracts all the characters from start to stop − 1 by step. You’re going to look more deeply at what all this means in just a moment.

All the offsets are optional, and they have the following default values:

Offset Default Value
start 0
stop len(a_string)
step 1

Here, start represents the index of the first character in the slice, while stop holds the index that stops the slicing operation. The third offset, step, allows you to decide how many characters the slicing will jump through on each iteration.

The step offset allows you to fine-tune how you extract desired characters from a string while skipping others:

>>>

>>> letters = "AaBbCcDd"

>>> # Get all characters relying on default offsets
>>> letters[::]
'AaBbCcDd'
>>> letters[:]
'AaBbCcDd'

>>> # Get every other character from 0 to the end
>>> letters[::2]
'ABCD'

>>> # Get every other character from 1 to the end
>>> letters[1::2]
'abcd'

Here, you first slice letters without providing explicit offset values to get a full copy of the original string. To this end, you can also use a slicing that omits the second colon (:). With step equal to 2, the slicing gets every other character from the target string. You can play around with different offsets to get a better sense of how slicing works.

Why are slicing and this third offset relevant to reversing strings in Python? The answer lies in how step works with negative values. If you provide a negative value to step, then the slicing runs backward, meaning from right to left.

For example, if you set step equal to -1, then you can build a slice that retrieves all the characters in reverse order:

>>>

>>> letters = "ABCDEF"

>>> letters[::-1]
'FEDCBA'

>>> letters
'ABCDEF'

This slicing returns all the characters from the right end of the string, where the index is equal to len(letters) - 1, back to the left end of the string, where the index is 0. When you use this trick, you get a copy of the original string in reverse order without affecting the original content of letters.

Another technique to create a reversed copy of an existing string is to use slice(). The signature of this built-in function is the following:

This function takes three arguments, with the same meaning of the offsets in the slicing operator, and returns a slice object representing the set of indices that result from calling range(start, stop, step).

You can use slice() to emulate the slicing [::-1] and reverse your strings quickly. Go ahead and run the following call to slice() inside square brackets:

>>>

>>> letters = "ABCDEF"

>>> letters[slice(None, None, -1)]
'FEDCBA'

Passing None to the first two arguments of slice() tells the function that you want to rely on its internal default behavior, which is the same as a standard slicing with no values for start and stop. In other words, passing None to start and stop means that you want a slice from the left end to the right end of the underlying sequence.

Reversing Strings With .join() and reversed()

The second and arguably the most Pythonic approach to reversing strings is to use reversed() along with str.join(). If you pass a string to reversed(), you get an iterator that yields characters in reverse order:

>>>

>>> greeting = reversed("Hello, World!")

>>> next(greeting)
'!'
>>> next(greeting)
'd'
>>> next(greeting)
'l'

When you call next() with greeting as an argument, you get each character from the right end of the original string.

An important point to note about reversed() is that the resulting iterator yields characters directly from the original string. In other words, it doesn’t create a new reversed string but reads characters backward from the existing one. This behavior is fairly efficient in terms of memory consumption and can be a fundamental win in some contexts and situations, such as iteration.

You can use the iterator that you get from calling reversed() directly as an argument to .join():

>>>

>>> "".join(reversed("Hello, World!"))
'!dlroW ,olleH'

In this single-line expression, you pass the result of calling reversed() directly as an argument to .join(). As a result, you get a reversed copy of the original input string. This combination of reversed() and .join() is an excellent option for reversing strings.

Generating Reversed Strings by Hand

So far, you’ve learned about core Python tools and techniques to reverse strings quickly. Most of the time, they’ll be your way to go. However, you might need to reverse a string by hand at some point in your coding adventure.

In this section, you’ll learn how to reverse strings using explicit loops and recursion. The final technique uses a functional programming approach with the help of Python’s reduce() function.

Reversing Strings in a Loop

The first technique you’ll use to reverse a string involves a for loop and the concatenation operator (+). With two strings as operands, this operator returns a new string that results from joining the original ones. The whole operation is known as concatenation.

Here’s a function that takes a string and reverses it in a loop using concatenation:

>>>

>>> def reversed_string(text):
...     result = ""
...     for char in text:
...         result = char + result
...     return result
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

In every iteration, the loop takes a subsequent character, char, from text and concatenates it with the current content of result. Note that result initially holds an empty string (""). The new intermediate string is then reassigned to result. At the end of the loop, result holds a new string as a reversed copy of the original one.

If you prefer using a while loop, then here’s what you can do to build a reversed copy of a given string:

>>>

>>> def reversed_string(text):
...     result = ""
...     index = len(text) - 1
...     while index >= 0:
...         result += text[index]
...         index -= 1
...     return result
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

Here, you first compute the index of the last character in the input string by using len(). The loop iterates from index down to and including 0. In every iteration, you use the augmented assignment operator (+=) to create an intermediate string that concatenates the content of result with the corresponding character from text. Again, the final result is a new string that results from reversing the input string.

Reversing Strings With Recursion

You can also use recursion to reverse strings. Recursion is when a function calls itself in its own body. To prevent infinite recursion, you should provide a base case that produces a result without calling the function again. The second component is the recursive case, which starts the recursive loop and performs most of the computation.

Here’s how you can define a recursive function that returns a reversed copy of a given string:

>>>

>>> def reversed_string(text):
...     if len(text) == 1:
...         return text
...     return reversed_string(text[1:]) + text[:1]
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

In this example, you first check for the base case. If the input string has exactly one character, you return the string back to the caller.

The last statement, which is the recursive case, calls reversed_string() itself. The call uses the slice text[1:] of the input string as an argument. This slice contains all the characters in text, except for the first one. The next step is to add the result of the recursive call together with the single-character string text[:1], which contains the first character of text.

A significant issue to note in the example above is that if you pass in a long string as an argument to reversed_string(), then you’ll get a RecursionError:

>>>

>>> very_long_greeting = "Hello, World!" * 1_000

>>> reversed_string(very_long_greeting)
Traceback (most recent call last):
    ...
RecursionError: maximum recursion depth exceeded while calling a Python object

Hitting Python’s default recursion limit is an important issue that you should consider in your code. However, if you really need to use recursion, then you still have the option to set the recursion limit manually.

You can check the recursion limit of your current Python interpreter by calling getrecursionlimit() from sys. By default, this value is usually 1000. You can tweak this limit using setrecursionlimit() from the same module, sys. With these functions, you can configure the Python environment so that your recursive solution can work. Go ahead and give it a try!

Using reduce() to Reverse Strings

If you prefer using a functional programming approach, you can use reduce() from functools to reverse strings. Python’s reduce() takes a folding or reduction function and an iterable as arguments. Then it applies the provided function to the items in the input iterable and returns a single cumulative value.

Here’s how you can take advantage of reduce() to reverse strings:

>>>

>>> from functools import reduce

>>> def reversed_string(text):
...     return reduce(lambda a, b: b + a, text)
...

>>> reversed_string("Hello, World!")
'!dlroW ,olleH'

In this example, the lambda function takes two strings and concatenates them in reverse order. The call to reduce() applies the lambda to text in a loop and builds a reversed copy of the original string.

Iterating Through Strings in Reverse

Sometimes you might want to iterate through existing strings in reverse order, a technique typically known as reverse iteration. Depending on your specific needs, you can do reverse iteration on strings by using one of the following options:

  • The reversed() built-in function
  • The slicing operator, [::-1]

Reverse iteration is arguably the most common use case of these tools, so in the following few sections, you’ll learn about how to use them in an iteration context.

The reversed() Built-in Function

The most readable and Pythonic approach to iterate over a string in reverse order is to use reversed(). You already learned about this function a few moments ago when you used it along with .join() to create reversed strings.

However, the main intent and use case of reversed() is to support reverse iteration on Python iterables. With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.

Here’s how you can iterate over a string in reverse order with reversed():

>>>

>>> greeting = "Hello, World!"

>>> for char in reversed(greeting):
...     print(char)
...
!
d
l
r
o
W

,
o
l
l
e
H

>>> reversed(greeting)
<reversed object at 0x7f17aa89e070>

The for loop in this example is very readable. The name of reversed() clearly expresses its intent and communicates that the function doesn’t produce any side effects on the input data. Since reversed() returns an iterator, the loop is also efficient regarding memory usage.

The Slicing Operator, [::-1]

The second approach to perform reverse iteration over strings is to use the extended slicing syntax you saw before in the a_string[::-1] example. Even though this approach won’t favor memory efficiency and readability, it still provides a quick way to iterate over a reversed copy of an existing string:

>>>

>>> greeting = "Hello, World!"

>>> for char in greeting[::-1]:
...     print(char)
...
!
d
l
r
o
W

,
o
l
l
e
H

>>> greeting[::-1]
'!dlroW ,olleH'

In this example, you apply the slicing operator on greeting to create a reversed copy of it. Then you use that new reversed string to feed the loop. In this case, you’re iterating over a new reversed string, so this solution is less memory-efficient than using reversed().

Creating a Custom Reversible String

If you’ve ever tried to reverse a Python list, then you know that lists have a handy method called .reverse() that reverses the underlying list in place. Since strings are immutable in Python, they don’t provide a similar method.

However, you can still create a custom string subclass with a .reverse() method that mimics list.reverse(). Here’s how you can do that:

>>>

>>> from collections import UserString

>>> class ReversibleString(UserString):
...     def reverse(self):
...         self.data = self.data[::-1]
...

ReversibleString inherits from UserString, which is a class from the collections module. UserString is a wrapper around the str built-in data type. It was specially designed for creating subclasses of str. UserString is handy when you need to create custom string-like classes with additional functionalities.

UserString provides the same functionality as a regular string. It also adds a public attribute called .data that holds and gives you access to the wrapped string object.

Inside ReversibleString, you create .reverse(). This method reverses the wrapped string in .data and reassigns the result back to .data. From the outside, calling .reverse() works like reversing the string in place. However, what it actually does is create a new string containing the original data in reverse order.

Here’s how ReversibleString works in practice:

>>>

>>> text = ReversibleString("Hello, World!")
>>> text
'Hello, World!'

>>> # Reverse the string in place
>>> text.reverse()
>>> text
'!dlroW ,olleH'

When you call .reverse() on text, the method acts as if you’re doing an in-place mutation of the underlying string. However, you’re actually creating a new string and assigning it back to the wrapped string. Note that text now holds the original string in reverse order.

Since UserString provides the same functionality as its superclass str, you can use reversed() out of the box to perform reverse iteration:

>>>

>>> text = ReversibleString("Hello, World!")

>>> # Support reverse iteration out of the box
>>> for char in reversed(text):
...     print(char)
...
!
d
l
r
o
W

,
o
l
l
e
H

>>> text
"Hello, World!"

Here, you call reversed() with text as an argument to feed a for loop. This call works as expected and returns the corresponding iterator because UserString inherits the required behavior from str. Note that calling reversed() doesn’t affect the original string.

Sorting Python Strings in Reverse Order

The last topic you’ll learn about is how to sort the characters of a string in reverse order. This can be handy when you’re working with strings in no particular order and you need to sort them in reverse alphabetical order.

To approach this problem, you can use sorted(). This built-in function returns a list containing all the items of the input iterable in order. Besides the input iterable, sorted() also accepts a reverse keyword argument. You can set this argument to True if you want the input iterable to be sorted in descending order:

>>>

>>> vowels = "eauoi"

>>> # Sort in ascending order
>>> sorted(vowels)
['a', 'e', 'i', 'o', 'u']

>>> # Sort in descending order
>>> sorted(vowels, reverse=True)
['u', 'o', 'i', 'e', 'a']

When you call sorted() with a string as an argument and reverse set to True, you get a list containing the characters of the input string in reverse or descending order. Since sorted() returns a list object, you need a way to turn that list back into a string. Again, you can use .join() just like you did in earlier sections:

>>>

>>> vowels = "eauoi"

>>> "".join(sorted(vowels, reverse=True))
'uoiea'

In this code snippet, you call .join() on an empty string, which plays the role of a separator. The argument to .join() is the result of calling sorted() with vowels as an argument and reverse set to True.

You can also take advantage of sorted() to iterate through a string in sorted and reversed order:

>>>

>>> for vowel in sorted(vowels, reverse=True):
...     print(vowel)
...
...
u
o
i
e
a

The reverse argument to sorted() allows you to sort iterables, including strings, in descending order. So, if you ever need a string’s characters sorted in reverse alphabetical order, then sorted() is for you.

Conclusion

Reversing and working with strings in reverse order can be a common task in programming. Python provides a set of tools and techniques that can help you perform string reversal quickly and efficiently. In this tutorial, you learned about those tools and techniques and how to take advantage of them in your string processing challenges.

In this tutorial, you learned how to:

  • Quickly build reversed strings through slicing
  • Create reversed copies of existing strings using reversed() and .join()
  • Use iteration and recursion to create reversed strings by hand
  • Loop over your strings in reverse order
  • Sort your strings in descending order using sorted()

Even though this topic might not have many exciting use cases by itself, understanding how to reverse strings can be useful in coding interviews for entry-level positions. You’ll also find that mastering the different ways to reverse a string can help you really conceptualize the immutability of strings in Python, which is a notable feature of the language.

Python String – это набор символов Юникода. Python имеет множество функций для обработки строк, но его строковая библиотека не поддерживает встроенную функцию «reverse()». Существуют другие способы как перевернуть строку в Python.

Использование цикла for

Изменим данную строку, используя цикл for.

 
def reverse_string(str): 
    str1 = ""   # Declaring empty string to store the reversed string 
    for i in str: 
        str1 = i + str1 
    return str1    # It will return the reverse string to the caller function 
    
str = "JavaTpoint"    # Given String      
print("The original string is: ",str) 
print("The reverse string is",reverse_string(str)) # Function call 

Выход:

('The original string is: ', 'JavaTpoint') 
('The reverse string is', 'tniopTavaJ') 

Объяснение:

В приведенном выше коде мы объявили функцию reverse_string() и передали аргумент str. В теле функции мы объявили пустую строковую переменную str1, которая будет содержать перевернутую строку.

Цикл for повторяет все элементы данной строки, соединяет каждый символ в начале и сохраняет его в переменной str1.

После полной итерации с помощью данного цикла  в вызывающей функции вернулась строка обратного порядка str1. Результат напечатан на экране.

Применение цикла while

Мы также можем перевернуть строку, используя цикл while. Разберем этот способ на следующем примере.

Пример –

 
# Reverse string 
# Using a while loop 
 
str = "JavaTpoint" #  string variable 
print ("The original string  is : ",str)  
reverse_String = ""  # Empty String 
count = len(str) # Find length of a string and save in count variable 
while count > 0:  
    reverse_String += str[ count - 1 ] # save the value of str[count-1] in reverseString 
    count = count - 1 # decrement index 
print ("The reversed string using a while loop is : ",reverse_String)# reversed string 

Выход:

('The original string  is : ', 'JavaTpoint') 
('The reversed string using a while loop is : ', 'tniopTavaJ') 

Объяснение:

В приведенном выше коде мы объявили переменную str, которая содержит строковое значение. Мы инициализировали цикл while значением строки.

На каждой итерации значение str [count – 1] соединялось с reverse_String и уменьшало значение. A while завершил свою итерацию и перевернул строку в обратном порядке.

С помощью оператора slice([])

Мы также можем перевернуть данную строку, используя расширенный оператор slice. Рассмотрим его применение в следующем примере.

Пример –

 
#  Reverse a string   
# using  slice syntax  
# reverse(str) Function to reverse a string  
def reverse(str):  
    str = str[::-1]  
    return str  
   
s = "JavaTpoint" 
print ("The original string  is : ",s)  
print ("The reversed string using extended slice operator  is : ",reverse(s)) 

Выход:

('The original string  is : ', 'JavaTpoint') 
('The reversed string(using extended slice syntax) is : ', 'tniopTavaJ') 

Объяснение:

Обычно оператор slice принимает три параметра – start, stop и step. Мы предоставили нулевое значение для начального и конечного индексов, что указывает на то, что начальный индекс равен 0, а конечный – n-1 по умолчанию. Размер шага -1 означает, что строка переходит от конца в позицию индекса 1.

Использование обратной функции reversed() с соединением

Python предоставляет функцию reversed() для переворота строки. Рассмотрим следующий пример.

Пример –

 
#reverse a string using reversed()  
# Function to reverse a string  
def reverse(str):  
 string = "".join(reversed(str)) # reversed() function inside the join() function 
 return string  
 
s = "JavaTpoint" 
 
print ("The original string is : ",s)  
print ("The reversed string using reversed() is : ",reverse(s) ) 

Выход:

('The original string is : ', 'JavaTpoint') 
('The reversed string using reversed() is : ', 'tniopTavaJ') 

Объяснение:

В теле функции мы объявили пустую строку, разделенную оператором .dot. Строка reversed() вернула обратную строку, которая соединилась с пустой строкой, разделенной с помощью функции join().

Применение рекурсии

Строку также можно перевернуть с помощью рекурсии. Рекурсия – это процесс, в котором функция вызывает сама себя. Рассмотрим следующий пример.

Пример –

 
# reverse a string   
# using recursion  
   
def reverse(str):  
    if len(str) == 0: # Checking the lenght of string 
        return str  
    else:  
        return reverse(str[1:]) + str[0]  
   
str = "Devansh Sharma"  
print ("The original string  is : ", str)    
print ("The reversed string(using recursion) is : ", reverse(str)) 

Выход:

('The original string is : ', 'JavaTpoint') 
('The reversed string(using reversed) is : ', 'tniopTavaJ') 

Объяснение:

В приведенном выше коде мы определили функцию, которая принимает строку в качестве аргумента.

В теле функции мы определили базовое условие рекурсии: если длина строки равна 0, то строка возвращается, а если нет, то мы вызываем функцию рекурсивно.

Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.

Python Reverse String – String Reversal in Python Explained with Examples

When you’re working with Python strings, there are times when you’ll have to reverse them, and work with their reversed copies instead.

But since Python strings are immutable, you cannot modify or reverse them in place.

In Python, there are a few different ways you can do this. And this tutorial will teach you how you can use string slicing, built-in methods, and recursion to reverse strings.

🎯 What You’ll Learn

  • Using Recursion to Reverse Strings: You’ll learn about how recursion works, and the intuition behind reversing strings using recursion.
  • Using  String Slicing to Reverse Strings: You’ll learn a much easier way to reverse Python strings.
  • Using Built-In Methods: You’ll learn yet another easy and intuitive way to reverse strings in Python.

So let’s get started.

How to Reverse Python Strings Using Recursion

Before learning how to use recursion to reverse strings, let’s start by understanding how recursion works.

Recursion is a powerful programming paradigm. To solve the problem of interest, a recursive function calls itself repeatedly, until a base case is reached.

Well, this is what you’ll have likely read about recursion before.

Let’s rephrase that definition in plain language now.

Recursion in Plain English

Suppose you’ve created a function to solve a problem.

  • The function is designed such that every time it’s called, it calls itself again.
  • These are called recursive function calls.
  • Each recursive function call does the same small amount of work.
  • And this goes on until there’s no work left to do. And the function doesn’t have to call itself any longer – this is called the base case.

How to Use Recursion to Reverse Strings

Let’s now discuss the motivation behind reversing strings intuitively. And to do this, consider the string "code".

Problem: Reverse the string "code".

9EzNJgPbbGbmddk3f_t55PSDTr7cP5fgdXJjCX9B_hPkP1GHzOq58PR3wkZPRSdU5_O7SC4g8tZOQVjlNx6Ya9jc00aeqgXP-fvGHECpU7lF64AWYraIz25u-6JbmvTXQCkI1HY_

Let’s forget recursion for a while, and start with what you know.

The first letter in the original string will be the last letter in the reversed string, yes?

  • So pull out the first letter – "c" here – and push it to the very end.
  • You’re now left with the string "ode". And the problem has reduced to reversing this substring "ode" [as "c" is already in the right place]

V4oyw-hYeZWzSzu0JULaKLzHynBWgQCAB-GJrEU6sb8j5u9OKY7DRIvDbYEw-2MrWY-rNcFmVYbkSQMfQyx6AjYG7j-flGQktEEwoZpO1H0Fl1Hkwq0MN2UpiPl3QYclrDWN91oU

  • You can do the very same task of pulling out the first letter yet again, now "o". And push it to the last slot available on the right.
  • Now that "c" and "o" have been taken care of, you’re left with the problem of reversing the substring "de".

IfSSH94VWA90ZxOSGqKUYBRUqFwT_nLY3W7vFJ4_jYdTIbUIQ17FabArbDqVv9cZ2jVdKoJTh0IFhKnoACscgipWLpL3iwfoeRV8FuFIABVPriynIqJabAccqr-UJHpScXBmuJQ9

  • Do it a couple more times – pull out "d" first, and then "e".

LDgbioxKdX1Mey1FpzF20KnWnCAVNIQZFWTczaB-IDiKhHOWudo5Wnx8qg5XyiBnA0r5UVwERxVYodPtcvSM39Irn7kJvMZ5X8UzdpVDwTfhKsr0uxNPadgMTCpmEy4qcgaQsiC2

  • You’re now left with reversing "" – an empty string.

sGHYP70tsai5P6CQdiJk5u8qOLEXNzq0Ab5q8r3mmO5HFJslYCSii17tw3khyo2SQuDBhdlpq05FZ7kvO2AOj65QGJdV_YK9E2aqN6VHx7E1YHETR-phtSJeTUchquxLpd-bCfjO

  • This is when you’ve put "e", "d", "o", and "c" in the correct positions, and you don’t have to do it any longer. In the context of recursion, you’ve reached the base case.

What did you do here?

  1. In each step, you did the same task of pulling out the first letter in each subsequent substring.
  2. And you reduced the problem to reversing a string that’s one letter shorter than it was before.

When did you stop?

When the string was empty – you didn’t have any more letters to pull out.

The illustration below sums up what we’ve done:

image-30

Intuition behind String Reversal (Image by the author)

Now that you’ve gotten the hang of how string reversal really works using recursion, let’s write some code.

Understanding the Recursion Call Stack

Here’s the Python function reverseString() that does exactly what you learned in the previous section.

The function reverseString() takes in any_string and returns the reversed copy of any_string.

def reverseString(any_string):
  if any_string == "":
    return any_string
  else:
    return reverseString(any_string[1:]) + any_string[:1]

You’ll have to understand how the recursive calls get pushed onto the stack when you call the function reverseString().

reverseString("code")

# Output
'edoc'
  • Say, you call the function reverseString() with "code" as the argument. This in turn makes a call to reverseString() with "ode" as the argument.
  • And this call makes a call to reverseString() yet again with "de" as the argument.
  • This continues until a call is finally made to reverseString() with an empty string "" as the argument.

For every function call, an activation record is created in the stack section of your computer’s memory.

And every subsequent function call’s activation record is pushed onto the top of the stack.

This is explained in the image below:

image-28

Call Stack (Image by the author)
  • You know that when the call is made with "", the function returns "" concatenated with "e" which is just "e". And its activation record gets popped off the stack.
  • The next call returns "ed", and the next returns "edo". And the activation record that’s popped off the stack finally returns "edoc" which is the reversed string.

Note that the activation record corresponding to each of the recursive calls gets popped off the stack once the values are returned – as shown in the call that returned "e".

For the sake of readability, I’ve omitted the ❌ in the illustration below. And the return values from the previous call have been indicated in green inside the call stack.

image-29

Return values from the recursive calls (Image by the author)

You can now call reverseString() with any valid Python string. Here are a few more examples.

reverseString("Python")

image-17

reverseString("Python Reverse String")

image-16

Well, that required quite a bit of effort. 😓 But I hope you’re now able to understand recursive calls better. 😊

In the next two sections, you’ll see easier ways to reverse strings. Let’s go. ✅

How to Reverse Python Strings Using String Slicing

You might as well reverse Python strings using string slicing. And you can slice through Python strings just the way you’d slice through Python lists.

Python String Slicing Explained

<string>[start: stop: step] returns a slice of the string – starting at the index start, extending all the way up to stop - 1, in steps of step.

Here are a few points about strings worth recollecting:

  • <string> is any valid Python string.
  • The start index is optional. If you don’t specify it, by default, the slice starts at the beginning of <string> (at index 0).
  • The stop index is also optional. If you don’t specify it, by default, the slice extends up to the end of <string>.
  • The optional step argument gives context on how you’d like to slice through <string>.
  • Let’s set step = 2. Now, the the slice would start from start and go up to stop - 1 , including every second character in the string.

Putting it all together, <string>[:::] returns a copy of the entire string.

Can you see why this is correct?🤔

Without the start index, the slice begins at index 0.

Without the end index, the slice extends up to the last character in the string.

Without the step argument, the slice includes all characters in the string.

  • You can also set negative values for step. And negative values will return string slices starting from the end of the string.
  • Set step = -1 : This returns a slice of the string starting from the last character, extending up to the first character. And it also includes every character.

Wait, isn’t this exactly the reversed string? 🙂 Yes, it is.

So <string>[::-1] returns a reversed copy of the string. ✅

any_string = "Python"

rev_string = any_string[::-1]

print(rev_string)

# Output
nohtyP

Head over to the next section to learn yet another way to reverse strings.

How to Reverse Python Strings Using the reversed() and the join() Methods

Let’s start by looking at what Python’s reversed() method does.

Python’s built-in reversed() function returns a reverse iterator over the values of a given sequence.

any_string = "Python"

Given a string like any_string, you can use the reversed() method to get the characters in the reversed order.

This is shown below:

for char in reversed(any_string):
  print(char)

image-13

Now that you have all your characters in the reversed order, you need to put them together into a string.

And Python’s join() method lets you do just that.

<sep>.join(<these>) joins <these> into a string with <sep> as the separator.

  • Here, <these> are the characters in the reversed order.
  • But what should <sep> be? Well, you don’t need any separator – you only want all the characters to go into the string at the right indices.
  • So what should you do then? Just insert a "" in the <sep> field, as shown:
"".join(reversed(any_string))

image-19

Just be careful not to insert a space between the opening and closing ".

If you do the following:

" ".join(reversed(any_string))

You’ll get a string where the characters are separated by a whitespace, and this isn’t what you want.

image-18

In this section, you’ve learned yet another Pythonic way to reverse Python strings.

Conclusion

Congratulations on making it this far! 🎉

To summarize, you’ve learned:

  • how to recursively reverse a string – go on until you have an empty string or have only one character left (this would work fine too, as one character reversed is itself),
  • how to use <string>[::-1] to get a reversed copy of  <string>, and
  • how to use "".join(reversed(<string>)) to get a reversed copy of <string>.

Hope you found this tutorial helpful and interesting. Happy coding! 😄



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Как написать слово задача
  • Как написать слово завуалировано
  • Как написать слово завершен
  • Как написать слово заботиться
  • Как написать слово жучка