This quick tutorial will show you how to reverse a string in Python, and provide example code.
Strings in Python
Strings in Python are defined using quotes or double quotes, and assigned to variables:
string1 = "This is a string" string2 = 'This is also a string'
Strings are used to store non-numeric values – things like names, words, sentences, and serialized data. There’s a lot you can do with Python strings.
Strings are immutable — meaning that once defined, they cannot be changed. However, the variable holding the string can be overwritten with a new, updated string.
A String is just a Sequence of Characters
A string is just an ordered sequence of characters. The value of the string is defined by the characters it contains, and the position they appear in.
How to Reverse Strings in Python
As a string is just an ordered sequence (or list) of characters, we can just use the slice() function or the slicing operator to create a new string, with the characters in a new (reversed) order.
myString = "This is a string" myStringReversed = myString[slice(None, None, -1)]
Or, if you’re looking to replace the original string with the reversed:
myString = "This is a string" myString = myString[slice(None, None, -1)]
The below has the same effect, with shortened syntax:
myString = "This is a string" myStringReversed = myString[::-1]
You can also use the reversed() built-in Python function – but as it returns a reverse iterator, its contents must be re-joined to form a string object.
myString = "This is a string" myStringReversed = "".join(reversed(myString))
If you are manipulating strings using loops and iterators, you can use the type() function to confirm that it has been converted back to a string type variable:
myString = "This is a string" myStringReversed = myString[slice(None, None, -1)] print(type(mySyStringReversed))
String variables will return their type as being str:
<class 'str'>