Python Cheat sheet

Useful tricks

# Terminate a Python script early.
    quit()
 
# For 1 statement on multiple lines, 
# use line continuation character (\).
# Good for blog post.
    def __str__(self):
        return "Name={}, Title={}, Hourly rate={}."\
                .format( self.name, self.title, self.__hourly_rate )

String

# Concatenation
    s1 = 'Open'
    s2 = 'Writings.net'
    print( s1+s2 ) # Output: OpenWritings.net
 
# Object to string: Use str() function
    import datetime
    now_str = "Today is " + str(datetime.datetime.now())
    print(now_str)
 
# Find and replace    
    string.replace(old_str, new_str, maxreplace) # maxreplace: Replace N occurrences matched.
 
# Replace using regular expression
    import re
    str="Example regex"
    test = re.sub(r"[Ee]", "a", str) # axampla ragax
 
# Join: string.join(iterable); iterable = list, string & tuple
    my_list = ['1', '3', '4', '5']
    separator = ','
    print( separator.join(my_list) ) # 1,3,4,5

If statement

List

Loop

Date & Time

Function

Last updated

Was this helpful?