Как перевернуть строку в python
Перейти к содержимому

Как перевернуть строку в python

  • автор:

5 способов перевернуть строку в Python 3

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

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

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

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

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

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

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

3. Рекурсия

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

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

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

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

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

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

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

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

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

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

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

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

Заключение

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

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

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

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

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

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

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

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

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

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

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

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

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

Переворот строки Python при помощи среза

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

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

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

Telegram Чат & Канал

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

Паблик VK

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Дональд Кнут

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

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

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

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

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

Reverse Strings in Python: reversed(), Slicing, and More

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.

Free Download: Get a sample chapter from Python Basics: A Practical Introduction to Python 3 to see how you can go from beginner to intermediate in Python with a complete curriculum, up-to-date for Python 3.8.

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:

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.

Note: A slicing operation finishes when it reaches the index equal to or greater than stop . This means that it never includes the item at that index, if any, in the final slice.

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

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:

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:

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:

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() :

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.

Note: Using .join() is the recommended approach to concatenate strings in Python. It’s clean, efficient, and Pythonic.

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

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.

Note: Since Python strings are immutable data types, you should keep in mind that the examples in this section use a wasteful technique. They rely on creating successive intermediate strings only to throw them away in the next iteration.

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

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:

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 :

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:

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() :

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:

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:

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:

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:

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:

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:

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:

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.

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

About Leodanis Pozo Ramos

Leodanis is an industrial engineer who loves Python and software development. He's a self-taught Python developer with 6+ years of experience. He's an avid technical writer with a growing number of articles published on Real Python and other sites.

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Aldren Santos

Bartosz Zaczyński

Sadie Parker

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal. Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

How do I reverse a string in Python?

There is no built in reverse function for Python’s str object. What is the best way of implementing this method?

If supplying a very concise answer, please elaborate on its efficiency. For example, whether the str object is converted to a different object, etc.

TylerH's user avatar

19 Answers 19

Slice notation takes the form [start:stop:step] . In this case, we omit the start and stop positions since we want the whole string. We also use step = -1 , which means, "repeatedly step from right to left by 1 character".

Mateen Ulhaq's user avatar

Paolo Bergantino's user avatar

@Paolo’s s[::-1] is fastest; a slower approach (maybe more readable, but that’s debatable) is ».join(reversed(s)) .

What is the best way of implementing a reverse function for strings?

My own experience with this question is academic. However, if you’re a pro looking for the quick answer, use a slice that steps by -1 :

or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join :

or for readability and reusability, put the slice in a function

Longer explanation

If you’re interested in the academic exposition, please keep reading.

There is no built-in reverse function in Python’s str object.

Here is a couple of things about Python’s strings you should know:

In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.

Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:

The subscript creates a slice by including a colon within the braces:

To create a slice outside of the braces, you’ll need to create a slice object:

A readable approach:

While ».join(reversed(‘foo’)) is readable, it requires calling a string method, str.join , on another called function, which can be rather relatively slow. Let’s put this in a function — we’ll come back to it:

Most performant approach:

Much faster is using a reverse slice:

But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let’s create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.

Implement as Function

To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:

And usage is simply:

What your teacher probably wants:

If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:

This is theoretically bad because, remember, strings are immutable — so every time where it looks like you’re appending a character onto your new_string , it’s theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.

Best Practice

Theoretically better is to collect your substrings in a list, and join them later:

However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.

Timings

Here are the timings:

CPython optimizes string concatenation, whereas other implementations may not:

. do not rely on CPython’s efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn’t present at all in implementations that don’t use refcounting. In performance sensitive parts of the library, the ».join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

Russia Must Remove Putin's user avatar

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

enter image description here

You can see that the time for the slicing ( 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.

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

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *