Whenever I’d find myself in a situation where I was required to perform a reverse operation, more often than not, I would use a for loop or resort to find some function like** reverse()** that had do the job for me.
But later on, to my shock I found, python has got another trick up it’s sleeve to solve this in a jiffy — Slicing Operation
You can use slicing [::-1]
syntax to reverse a string, tuple or a list as well
string = 'John Wick'
print(string[::-1]) ## logs: 'kciW nhoJ'
tup = (23, 45, 12, 56)
print(tup[::-1]) ## logs: (56, 12, 45, 23)
l = ['john', 'baba', 'yaga', 'wick']
print(l[::-1]) ## logs: ['wick', 'yaga', 'baba', 'john']
2. Check if given string is a palindrome →
Pretty easy, right? A lot of different approach comes to our mind when we think about this ways to solve this problem. But guess, one of the most simple way to solve this problem could again be the slicing operation.
Using the above discussed reversing trick, one line of code would be enough to check whether a given string is a palindrome or not. Firstly, we use string[::-1]
to reverse the string and then we simply compare our original string with the reversed string string == string[::-1]
to get the result.
string = 'aibohphobia'
print('Palindrome' if string == string[::-1] else 'No Plaindrome')
## print: Palindrome
string = 'johnwick'
print('Palindrome' if string == string[::-1] else 'No Plaindrome')
## print: No Plaindrome
#tech #programming #python #coding