Simplicity is Python’s way to solve problem.Python’s cool tricks for programming.
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
Guide to Python Programming Language
This article will explore how to generate QR code in Python and some useful creation features from pyqrcode library. QR codes recently became more popular than ever before, yet few people know that the first iterations of QR codes were created back in 1990s in Japan for the automotive industry.
Python is an interpreted, high-level, powerful general-purpose programming language. You may ask, Python’s a snake right? and Why is this programming language named after it?
Python Hello World Program - Your first step towards Python world. Learn how to create the Hello World Python program in PyCharm.
Python Programming Tutorials For Beginners