Python is a no-BS programming language. Readability and
simplicity of design are two of the biggest reasons for its
immense popularity.
The following snippets/tricks will help for Everyday Problems you face while coding in Python.
#
Reversing a String
The following snippet reverses a string using the Python
slicing operation.
# Reversing a string using slicing
my_string = "ABCDE"
reversed_string = my_string[::-1]
print(reversed_string)
# Output
# EDCBA
#
Using rhe Title Case (First Letter Caps)
The following snippet can be used to convert a string to title case. This is done using the title() method of the string class.
my_string = "my name is chaitanya baweja"
# using the title() function of string class
new_string = my_string.title()
print(new_string)
# Output
# My Name Is Chaitanya Baweja
#
Printing a String or a List n Times
You can use multiplication (*) with strings or lists. This allows us to multiply them as many times as we like.
n = 3 # number of repetitions
my_string = "abcd"
my_list = [1,2,3]
print(my_string*n)
# abcdabcdabcd
print(my_list*n)
# [1,2,3,1,2,3,1,2,3]
#
List Comprehension
List comprehension provides us with an elegant way of creating lists based on other lists.
The following snippet creates a new list by multiplying each element of the old list by two.
# Multiplying each element in a list by 2
original_list = [1,2,3,4]
new_list = [2*x for x in original_list]
print(new_list)
# [2,4,6,8]
#
Swap Values Between Two Variables
Python makes it quite simple to swap values between two variables without using another variable.
a = 1
b = 2
a, b = b, a
print(a) # 2
print(b) # 1
#
Split a String Into a List of Substrings
We can split a string into a list of substrings using the .split() method in the string class. You can also pass as an argument the separator on which you wish to split.
string_1 = "My name is Chaitanya Baweja"
string_2 = "sample/ string 2"
# default separator ' '
print(string_1.split())
# ['My', 'name', 'is', 'Chaitanya', 'Baweja']
# defining separator as '/'
print(string_2.split('/'))
# ['sample', ' string 2']
#
Combining a List of Strings Into a Single String
The join() method combines a list of strings passed as an argument into a single string. In our case, we separate them using the comma separator.
list_of_strings = ['My', 'name', 'is', 'Chaitanya', 'Baweja']
# Using join with the comma separator
print(','.join(list_of_strings))
# Output
# My,name,is,Chaitanya,Baweja
#
Using the try-except-else Block
Error handling in Python can be done easily using the try/except block. Adding an else statement to this block might be useful. It’s run when there is no exception raised in the try block.
If you need to run something irrespective of exception, use finally.
a, b = 1,0
try:
print(a/b)
# exception raised when b is 0
except ZeroDivisionError:
print("division by zero")
else:
print("no exceptions raised")
finally:
print("Run this always")
#
Check the Memory Usage of an Object
The following script can be used to check the memory usage of an object.
import sys
num = 21
print(sys.getsizeof(num))
# In Python 2, 24
# In Python 3, 28
#
Digitize
The following snippet will convert an integer into a list of digits.
num = 123456
# using map
list_of_digits = list(map(int, str(num)))
print(list_of_digits)
# [1, 2, 3, 4, 5, 6]
# using list comprehension
list_of_digits = [int(x) for x in str(num)]
print(list_of_digits)
# [1, 2, 3, 4, 5, 6]
# Even simpler approach
list_of_digits = list(str(num))
print(list_of_digits)
# [1, 2, 3, 4, 5, 6]
Check more at Code Perfect Plus