Type casting in Python

Explicit conversion To cast a variable to a string just use the str() function. my_str = str('32') # this is just a regular explicit intialization print(my_str) my_str = str(32) # int to str print(my_str) my_str = str(32.0) # float to…

User input in the command line in Python

If you need to interact with the user when running your program in a command line, to ask for a piece of information, you can use the input() function in Python 3. country = input("What is your country? ") #user…

Checking if a tuple is empty in Python

The pythonic way to check if a tuple is empty is using the not operator. my_tuple = () if not my_tuple: print("My tuple is empty") To check the opposite, if the tuple is not empty: my_tuple = ('amazon', 'microsoft') if…

Checking if a dictionary is empty in Python

The pythonic way to check if a dictionary is empty is using the not operator. my_dict = {} if not my_dict: print("My dictionary is empty!!!") To check the opposite, if the dict is not empty: my_dict = {1:'amazon', 2:'microsoft'} if…

Checking if a string is empty in Python

The pythonic way to check if a string is empty is using the not operator. my_string = '' if not my_string: print("My string is empty!!!") To check the opposite, if the string is not empty: my_string = 'amazon, microsoft' if…

Checking if a list is empty in Python

The pythonic way to check if a list is empty is using the not operator. my_list = [] if not my_list: print("My list is empty!!!") To check the opposite, if the list is not empty: my_list = ['amazon', 'microsoft'] if…

CORS on Django REST Framework

In the post Django REST Framework: API in a few minutes in Python, I showed you how to build your very first API in Python. But there is one minor problem, if you test your API with another application, like…

String Swap Case in Python

Use the swapcase() method to transform the upper case characters into a lower case and vice versa. regular_text = "This IS a reguLar text." swapped_case_text = regular_text.swapcase() print(regular_text) #This IS a reguLar text. print(swapped_case_text) #tHIS is A REGUlAR TEXT. Notice…

String Title Case in Python

Use the title() method to transform the first letter in each word into upper case and the rest of characters into lower case. regular_text = "This is a regular text." title_case_text = regular_text.title() print(regular_text) #This is a regular text. print(title_case_text)…