I’ve divided these articles into ten parts from beginner level to senior. Will be sharing some useful tips and tricks for Python newbies that will make your life much easier.
Tip 1: Reducing Your Code
It might not seem necessary when you see the below code snippet but making your code more compact goes a long way, when building big programs.
Most people use the below method which is a bit longer approach when assigning variables, example:
There is nothing wrong with this approach, but there is a better method which will make your code more readable.
Tip 2: Changing The Color Of The Message Text
Let’s say we want to display the following message (“Welcome and enjoy your shopping”) in blue, we can simply choose the color of our choice using escape sequences before our text.
I have chosen the code for blue, but they are various options to choose from, I usually use https://www.codegrepper.com/code-examples/python/python+ansi+escape+sequences+color+collection
Tip 3: Split Long Strings into multiple lines
Long strings in one line can look confusing and is not pleasant to read, so we can separate these strings into multiple lines.
Tip 4: Slicing Strings With Negative Elements
Sequences including strings are indexed from 0 and from left to right, T is index 0 and our first element.
So what if we wanted to index from the back? Well we can use the right to left approach using the negative index.
The value -3 returns the element e, meaning a is -1, k is -2 and e is -3.
Tip 5: Reversing Strings
In the code snippet below we pass in the starting and end position into our square brackets, followed by -1 meaning we want to work from the right to the left.
Tip 6: Using The Reverse Function To Reverse A List Of Numbers
One could say the built in reverse function is “friendlier” than slicing, but it is good to note that it is restrictive and ideal for numbers.
Tip 7: Searching For A Substring in Another String
Strings are similar to other sequential, linear data types, so we can use the in operator to find any character.
Tip 8: Using A Single Line if Statement
There is nothing wrong with the above statement, but we want to simplify things for ourselves and whoever needs to read our code, hence we can summarize the above statement/condition to one line.
Tip 9: Using The ID Function
This is a built-in Python function that returns the unique id of the object, this is considered to be the address of the object in memory.