keywords: Python Common Syntax

Print

Python2

print("a=%d,b=%d" % (f(x,n), g(x,n)))

Python3

print('x={:d}, y={:d}'.format(f(x,n), g(x,n)))

Python3.6

print(f'a={f(x,n):d}, b={g(x,n):d}')

How to print like printf in Python3?
https://stackoverflow.com/questions/19457227/how-to-print-like-printf-in-python3

Case-insensitive string comparison

Python2

string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print "The strings are the same (case insensitive)"
else:
    print "The strings are not the same (case insensitive)"

Python3

s = 'ß'
s.lower() #  'ß'
s.casefold() # 'ss'

casefold() not only can be used for ASCII strings, but also for Non-ASCII strings, e.g. German script

How do I do a case-insensitive string comparison?
https://stackoverflow.com/questions/319426/how-do-i-do-a-case-insensitive-string-comparison/29247821#29247821

Object Type Checking

Way 1:

>>> type([]) is list
True
>>> type({}) is dict
True
>>> type('') is str
True
>>> type(0) is int
True
>>> type({})
<type 'dict'>
>>> type([])
<type 'list'>

Way 2:

>>> isinstance(b, Test1)
True
>>> isinstance(b, Test2)
True
>>> isinstance(a, Test1)
True
>>> isinstance(a, Test2)
False
>>> isinstance([], list)
True
>>> isinstance({}, dict)
True

Determine the type of an object?
https://stackoverflow.com/questions/2225038/determine-the-type-of-an-object

If Syntax

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

string

String Append Double Quotes

Beautiful usage in python

b = '"{}"'.format(a)

in python 3.6 (or above)

b = f'"{a}"'

How to append double quotes to a string and store as new string?
https://stackoverflow.com/questions/45208090/python-how-to-append-double-quotes-to-a-string-and-store-as-new-string

Object Iterator

List Iterator

e.g. 1:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    next(a)
... 
0
1
2
3
4
5
6
7
8
9

e.g. 2:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    _ = next(a)
... 
0
2
4
6
8

Python list iterator behavior and next(iterator)
https://stackoverflow.com/questions/16814984/python-list-iterator-behavior-and-nextiterator

Dictionary Iterator

Python 2.x:

for key, val in PIX0.iteritems():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
    print ("Nice Job!")
    count = count + 1
else:
    print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

Python 3.x:

for key, val in PIX0.items():
NUM = input("Which standard has a resolution of {!r}?".format(val))
if NUM == key:
    print ("Nice Job!")
    count = count + 1
else:
    print("I'm sorry but thats wrong. The correct answer was: {!r}.".format(key))

Python 3.x:

 for key in obj.keys():
    val = obj.get(key)

Python3 Dictionary iterate through values?
https://stackoverflow.com/questions/30446449/python3-dictionary-iterate-through-values


招取英灵毅魄,长绕贺兰山。---邓千江· 《望海潮》