Grammer Tips for Python 3

In this article, I would like to share some Python Grammer tips for beginner.

🎳 String

In Python, there are two type of string.

  • str = u'...' => A sequence of Unicode characters (UTF-16 or UTF-32)
  • bytes = b'...' => A sequence of octets (integers between 0 and 255)

convert string to lowercase

s = "Kilometer"

Remove all line breaks from a long string of text

'test\n\r'.replace('\n', ' ').replace('\r', '') #=> 'test'

Variable expansion in String

'Number is {0}、text is {1}'.format(number, text)

Search a substring

s = "This be a string"
if s.find("is") == -1:
print "No 'is' here!"

if "is" in s:
print "No 'is' here!"

string => byte

You can encode a str to a bytes object.

# => b'\xef\xbb\xbf'

byte => string

# => '€'

🐰 List/Array

Get the number of elements in a list

>> len([1,2,3])

Convert list to string

list1 = ['1', '2', '3']
str1 = ', '.join(list1) #=> '1, 2, 3'


Converting multi dimensional array to flatten array is as follows:

l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
for sublist in l:
for item in sublist:

How to make a comma-separated string from a list of strings

myList = ['a','b','c','d']
myString = ','.join(myList)

🚜 Dict

Wether find key

if "key" in dict:
# do something

🍮 Float/Decimal

Convert float to Decimal

format(f, ".15g")

🎂 Tuple

Add variable to tuple

a = (1, 2, 3)
b = a + (4,) #=> (1, 2, 3, 4)

🎉 Regex

Extract pattern matches

s = "name my_user_name is valid"
p = re.compile("name (.*) is valid")
result = #=> my_user_name
p = re.compile('name (.*) is valid')
s = """
someline abc
someother line
name my_user_name is valid
some more lines"""
p.findall(s) #=> ['my_user_name']

string.replace with regular expression

import re

line = re.sub(
"interfaceOpDataFile %s" % fileIn,

Remove specific pattern from text

This is example for removing HTML tags/formatting from a string:

import re
def strip_html_tag(data):
p = re.compile(r'<.*?>')
return p.sub('', data)

strip_html_tag('<a href="" class="bar">I Want This <b>text!</b></a>')
#=> 'I Want This text!'

😀 Datetime


import datetime

String to Datetime

pip install dateutil and add the following code:

from dateutil import parser
dt = parser.parse("Aug 28 1999 12:00AM")

Convert unix timestamp to readable date

from datetime import datetime

# No miliseconds

# With miliseconds
s = 1236472051807 / 1000.0
datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f') #=> '2009-03-08 09:27:31.807000'

Get current time in milliseconds

import time
millis = int(round(time.time() * 1000))
print millis

🐯 Grammar

None is instead of null

In Python, the null object is the singleton None.

Ternary operator

x = "OK" if n == 10 else "NG"

Throw/Raise Error

raise RuntimeError('specific message') from error

super().__init__() methods

class Polygon(object):
def __init__(self, id): = id

class Rectangle(Polygon):
def __init__(self, id, width, height):
super(self.__class__, self).__init__(id)
self.shape = (width, height)

Keyword argument for method

def func(a, b, *, option1=1, option2=2):

func(a, b, option1=10, option2=20)
func(a, b, c) # エラー 固定変数は2つ
func(a, b, opton1=10) # エラー 存在しないキーワード

How to import the class in same dir

from .user import User

Import a module given the full path

import sys
import Mock

Get type information of object

>>> isinstance([0, 10, 20, 30], list)
>>> isinstance(50, list)

str = "test"

Object unique identifier


🚕 Etc

Load multiple JSON object

JSON decoder can not load multiple JSON object like this:

{"name": "foo"}
{"name": "bar"}

It makes some error json.decoder.JSONDecodeError: Extra data..

If you want to load multiple JSON object, please use as follows:

import json
from json.decoder import WHITESPACE

def loads_iter(s):
size = len(s)
decoder = json.JSONDecoder()

end = 0
while True:
idx = WHITESPACE.match(s[end:]).end()
i = end + idx
if i >= size:
ob, end = decoder.raw_decode(s, i)
yield ob

Generate CSV file

Generate CSV file from list(array):

import csv

items = [
['John', 28],
['Sara', 22]

with open('/app/job_items.csv', 'w', encoding='utf8') as f:
wr = csv.writer(f, quoting=csv.QUOTE_ALL, lineterminator='\n')
wr.writerow(['name', 'age'])
for i in items:

# Write string data as CSV
# csvwriter.writerow([i])

Write data to file

file = open(“testfile.txt”, ”w”)  
file.write(“Hello World”)

How to access environment variables

import os

Check existence of an environment variable

if os.environ.get('abc'):
#abc is set to True


from functools import lru_cache

def fib_memoized(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)

🗻 References

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!