Python >> Tips and Tricks 1

2022-08-13 Python

Table of Contents

This tutorial will explain how to split a string, import module, use class and object, reverse a list, use args and kwargs, use exception.

Python

Python How to split a string to a list

Split a string by default delimiter (space)

# Split a string
str = "Hello World"
print(str.split())

['Hello', 'World']

Split a string by custom delimiter

# Split a string by custom delimiter
str2= "A,B,C"
print(str2.split(','))

['A', 'B', 'C']

Python how to import module

Import module

# Import module
import os
print(os.getcwd())

/Your/Current/Working/Directory

Import module from subdirectory

# Import module from subdirectory
import sys
sys.path.append('/Path/To/subdirectory')
import mymodule
print(mymodule.myfunc())

Using relative path to import module

# Using relative path to import module
import sys
sys.path.append('./subdirectory')
import mymodule
print(mymodule.myfunc())

Using from … import

# Using from import
from subdirectory import mymodule
print(mymodule.myfunc())

Aliasing Modules

# Aliasing Modules
import os as myos
print(myos.getcwd())

/Your/Current/Working/Directory

Python how to use Class and Object

Create a class

# Create a class
class MyClass:
    def __init__(self, name):
        self.name = name
    def say_hello(self):
        print(f"Hello, {self.name}")

Create an object

# Create an object
my_object = MyClass("John")
my_object.say_hello()

Hello, John

Python how to reverse a list

Reverse a whole list

# Reverse a list
my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list)

[5, 4, 3, 2, 1]

Reverse a List Using Slicing Operator

# Reverse a list using slicing operator
my_list = [1, 2, 3, 4, 5]
print(my_list[::-1])

[5, 4, 3, 2, 1]

Accessing Elements in Reversed Order

# Accessing Elements in Reversed Order
my_list = ["a", "b", "c"]
for e in reversed(my_list):
    print(e)
c
b
a

Python how to use **kwargs

Using kwargs

# Using kwargs
def myfunc(**kwargs):
    print(kwargs)
myfunc(a=1, b=2, c=3)

{'a': 1, 'b': 2, 'c': 3}

Using kwargs with positional arguments

# Using kwargs with positional arguments
def myfunc(a, b, c, **kwargs):
    print(kwargs)
myfunc(1, 2, 3, d=4, e=5)

{'d': 4, 'e': 5}

Python how to use *args

Using *args

# Using *args
def myfunc(*args):
    print(args)
myfunc(1, 2, 3, 4, 5)

(1, 2, 3, 4, 5)

Using *args with positional arguments

# Using *args with positional arguments
def myfunc(a, b, c, *args):
    print(args)
myfunc(1, 2, 3, 4, 5)

(4, 5)

Python how to use exception

Raise/Throw exception

# Throw exception
def myfunc():
    raise Exception("This is an exception")
myfunc()

Python Tips and Triks

Catch all/any exceptions

# Catch exception
try:
    myfunc()
except Exception as e:
    print(e)
This is an exception

Define custom exception

# Define custom exception
class MyException(Exception):
    pass
def myfunc2():
    raise MyException("This is an MyException")
myfunc2()

Python Tips and Triks

Catch specific exception

# Catch specific exception
try:
    myfunc2()
except MyException as me:
    print(me)
This is an MyException

Subscribe and be the FIRST reader of our latest articles

* indicates required

Contact us