SwadhyAI Notes

All Python notes

Python How To Reverse a String 🔄

Reverse a String

Learn how to reverse a string in Python.

✨ Using Slicing

There is no built-in function to reverse a String in Python.

The fastest (and easiest?) way is to use a slice that steps backwards, -1.

python
txt = "Hello World"[::-1]
print(txt)

✨ Create a Function

If you want to have a function that you can send strings into, and get them back reversed, you can create a function.

python
def my_function(x):
  return x[::-1]

mytxt = my_function("I wonder how this text looks like backwards")

print(mytxt)

✨ Pro Tip

Slicing is a very powerful feature in Python that allows you to access parts of sequences like strings, lists, and tuples.