Как написать слово наоборот питон

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

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

Обзор трех основных способов перевернуть строку 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 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»

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.

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

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 вместе с вами, читаю, собираю и записываю информацию опытных программистов.

Kedar Kodgire Follow
Kedar is a tech blogger, UI/UX designer and developer, cloud engineer, and machine-learning enthusiast. He’s passionate about exploring new technologies and sharing them with everyone.


November 10, 2021


4 min read
1195

A sequence of characters forms a string in Python. However, in Python, strings are immutable — changing strings doesn’t alter the string, but it creates a new one. Hence there are no inbuilt methods to reverse a string in Python.

Well, don’t worry about it; we have a few workarounds to achieve the task of reversing the string. Let’s look at these methods one by one.

Slicing

This is one of the easiest and shortest ways to reverse a string. Slicing in Python accepts three parameters as mentioned below:

  1. Start index
  2. End index
  3. Step (optional, but we need it in our case)

There are two ways to use this operator using the extended slice syntax or the slice function.

Extended slice

>>> 'raed ,tsop eht ot emocleW'[::-1]
'Welcome to the post, dear.'

>>> x = '.gnidaer rof sknahT'
>>> x[::-1]
'Thanks for reading.'

In the example above, we haven’t provided any start and end index. By default, the start index is considered 0, the end index as n-1. We mention step as -1, which means the string continues the traverse from the end and goes to the beginning providing the desired result. As shown above, we can also assign the string to a variable and perform this operation.

slice method

>>> step = -1
>>> stop = None
>>> start = None
>>> slicing=slice(start, stop, step)
>>> '.siht gniyojne era uoy epoh I'[slicing]
'I hope you are enjoying this.'

Here we assign values -1 to step and None for a start and stop index. Then, we use the slice() function, store the object into the variable slicing, and use it with the string later.

reversed and join

In this method, we use two inbuilt functions: reversed and join.

reversed

>>> for letter in reversed('abc'):
...     print(letter)
...
c
b
a

The reversed method returns the iterator (which allows us to access the elements one by one), which we can access in the reverse order.

join

>>> ''.join(['a','b','c'])
'abc'

The join method takes values from the iterator and sews them into a string. The quotes at the beginning are used to specify a character or a pattern to join the string. We don’t want any pattern; hence we left it blank.

Using reversed and join together

By using both of these functions together, we can achieve the following result:

>>> custom_string = '.flesym ecudortni em teL'
>>> ''.join(reversed(custom_string))
'Let me introduce myself.'

Here we pass the string to the reversed function and feed the same to the join function, which provides the required result.

Loops

for loop

>>> def reverse(input_string):
...     new_string = ''
...     for character in input_string:
...             new_string = character + new_string
...     return new_string
...
>>> reverse('radeK si eman yM')
'My name is Kedar'
  1. Here, we are creating a function reverse, which accepts a string as an input.
  2. Then we initialize an empty string, and it will be used for storing output.
  3. Iterating through each character in the input_string, we add the new_string to that character.
  4. Once the loop is completed, we get the desired result, and we return it.

while loop

Similar actions can be performed using the while loop. But, first, let’s look at the example:

>>> def w_reverse(input_string):
...     new_string = ''
...     count = len(input_string) - 1
...     while count >= 0:
...             new_string = new_string + input_string[count]
...             count = count - 1
...     return new_string

>>> w_reverse('?uoy era woH')
'How are you?'
  1. Here, we are creating a function and initializing a new variable, the same as the previous example
  2. Now we take the length of the input string and subtract it by 1 because the index in Python starts from 0. The action of subtracting can be done in another way as well, i.e., new_string = new_string + input_string[count - 1]
  3. In the while loop, we check if the calculated length is greater than or equal to zero. This part should be done carefully because any mistakes can lead a program to an infinite loop
  4. Next, we add the new string to the iterated character and reduce the count by 1. We reduce the count because we need to stop once the iteration is over; else, it will cause an infinite loop
  5. Once the count is less than zero, the while loop gets completed, and we get the result

Recursion

>>> def reverse(str):
...     if len(str) == 0: # Checking the length of string
...         return str
...     else:
...         return reverse(str[1:]) + str[0]
...
>>> reverse('.syaw tnereffid ni gnirts nohtyP a esrever ot elba eb dluohs uoy ,won yB')
'By now, you should be able to reverse a Python string in different ways.'

Recursion is a concept in which the function calls itself. In our case, we are defining a function that takes string input. Firstly we check if the length of the received string is equal to zero; if it is, we return the string. Then, we call the same function and pass the input except for the first character if this condition fails. The result will be joined with the first omitted character.

This function will end only when the length of the input string is zero.

List reverse and join

This is the last method that we are going to look at today. Here we convert the input string into the list of characters. Then we use the reverse method on top of it. Finally, we use the join method to join the characters of the reversed list:

>>> def list_reverse(input_string):
...     input_list = list(input_string)
...     input_list.reverse()
...     return ''.join(input_list)
...
>>>
>>> list_reverse('dohtem tsal ehT')
'The last method'

Conclusion

Working with strings and reversing them can be a common task in any programming language. Even though this topic may not have compelling use cases, this knowledge will be helpful for you in your coding interviews.

Here is a summary of the strategies used in this post:

  • Extended slices ([::-1]) are the shortest and easiest way to reverse a string. However, we can also use the slice() method to make it readable
  • Using Join along with the inbuilt reversed method, which returns an iterable
  • Working with loops for and while is the most straightforward way to reverse a string
  • Use self-calling functions — recursions to reverse a string
  • Utilizing the inbuilt reverse method in Python to reverse a list and join it

There are multiple ways to solve a problem in computer science, but not every solution is efficient. So now that we have seen different ways to reverse a Python string, I encourage you to calculate runtimes for the various ways you learned above. In this way, you get to try each of these methods by yourself, so you get a good hold of it and have the fastest strategy at the end.

Let me know in the comments which one is the fastest.

Cut through the noise of traditional error reporting with LogRocket

LogRocket Dashboard Free Trial Banner

LogRocket is a digital experience analytics solution that shields you from the hundreds of false-positive errors alerts to just a few truly important items. LogRocket tells you the most impactful bugs and UX issues actually impacting users in your applications.

Then, use session replay with deep technical telemetry to see exactly what the user saw and what caused the problem, as if you were looking over their shoulder.

LogRocket automatically aggregates client side errors, JS exceptions, frontend performance metrics, and user interactions. Then LogRocket uses machine learning to tell you which problems are affecting the most users and provides the context you need to fix it.

Focus on the bugs that matter — try LogRocket today.

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