Since there is no built-in feature, if you want to know how to flip a string in Python, you must use one of two McGyver techniques. Fortunately, these are still relatively straightforward and do not take long to learn. Here’s what you need to know.
How to flip a string in Python with cutting
The first way to turn a string is to use a piece that goes backwards. Discs in Python allow you to return bits of data from strings, tuplings, and lists. This is useful if you ever want to retrieve any items from a list or if you want to take a piece of a string.
A disc is usually used to provide a range such as “4-7”:
stringy = "Hello world" print(stringy[4:10])
This will return “o worl”. Remember that the first value in a string or list has the index “0”. This applies to most programming languages. If we leave a number blank and only add a colon, Python will refer to the first and last value, respectively.
Also read: When to use lists rather than dictionaries in Python
We can also add a third number if we want to define the “step.” For example:
This shows us the values 4-10, but skips all other entries!
Which of course gives us the reverse step:
stringy = "Hello world" print(stringy[10:4:-1])
Combine these two techniques and you get a disc that moves backwards through the entire string:
This begins and ends at the beginning and end of the string respectively and moves backwards. There you have it: this is how you can flip a string in Python!
How to turn a string in Python manually
You can alternatively turn your string manually. This can be useful if you ever need to check the values as you run through the string:
This method goes through the string backwards and starts at the last position in the string. It then moves backward through each value and adds that value to a new string. The result is a new, inverted string.
stringy = "Hello World" reversedStringy = "" index = len(stringy) while index > 0: reversedString = reversedStringy + stringy[index - 1] index = index - 1 print(reversedStringy)
This method is a bit slower and more cumbersome, but it is also more flexible to suit your needs.
Now you do not know a but two methods to flip a string in Python! Let us know what other methods you use in the comments below. And don’t forget to check out our guide to the best online Python courses. There you can find some great deals on courses that give you a complete Python training; takes you from beginner to pro for a fraction of the usual cost!