keywords: Python Common Syntax

Basic syntax

Global variables

Python2:

global c

Python 3:

nonlocal c

If assign to a variable that wasn’t decorated as global, assignment will fail with error:

UnboundLocalError: local variable 'cnt' referenced before assignment

Origin:
https://stackoverflow.com/a/370363/1645289

If Syntax
if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

String

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

You want to format a string with the character { or }, you just have to double them. format { with f'{{' and } with f'}}'

name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')

output:

Hello bob ! I want to print } and { or { }
String Format
my_string = "{}, is a {} {} science portal for {}"
print(my_string.format("GeeksforGeeks", "computer", "geeks"))
file_path = '{}/test.txt'.format(work_dir)

Origin:
https://www.geeksforgeeks.org/python-string-format-method/

String Replace
txt = "I like bananas"
x = txt.replace("bananas", "apples")
print(x) #I like apples
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

Zero Padding (Number Formatting)
i = 255
print('Zero Padding: {:08}'.format(i))
# Zero Padding: 00000255
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

Split

Code:

string = "one,two,three"
words = string.split(',')
print(words)

Output:

['one', 'two', 'three']

Origin:
https://www.geeksforgeeks.org/python-string-split/

Substring
string = "freeCodeCamp"
print(string[2:6])

Output:

eeCo

Origin:
https://www.freecodecamp.org/news/how-to-substring-a-string-in-python/

Regex

How to replace string with regex?

import re
line = re.sub(r"</?\[\d+>", "", line)

Origin:
https://stackoverflow.com/a/5658439/1645289

How to do a string pattern matching using Regex?

import re
title_regex = re.compile(r'".*"$')
title = title_regex.search('title= "Hello World"')
print(title.group())

Output: "Hello World".

How to generate random password string
import string
import random
import secrets

def id_generator(size=16, chars=string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation):
    return ''.join(secrets.choice(chars) for i in range(size))
    
print(id_generator())

Reference:
https://flexiple.com/generate-random-string-python/

Object

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

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

Class & Struct
class image:
    def __init__(self):
        self.address = ''
        self.label = 1
        self.storage = 1

single_image = image()
single_image.address = 'xxx'
single_image.label = 3
single_image.storage = 10

images = []
images.append(single_image)

Origin:
https://stackoverflow.com/q/52489949/1645289

Sort a list with struct data

Following on from the above:

import operator
images.sort(key=operator.attrgetter('storage'))

Origin: https://stackoverflow.com/a/52489975/1645289

Array

Append
aList = []
aList.append( 1001 )
aList.append( 'abc' )
print(aList) #[1001, 'abc']
Get item by index
aList = [1001, 'abc']
print(aList[1]) #abc
Find item index
animals = ['cat', 'dog', 'rabbit', 'horse']
index = animals.index('rabbit')
print(index) #2
Remove item
aList = [1001, 'abc']
del aList[1]    # removing second element
print(aList)    # Output: [1001]
del aList       # deleting entire array
print(aList)    # Error: array is not defined

Dictionary

Dictionary Insert (add item)
  1. Use the square bracket notation ([])

     my_dict = {}
     my_dict['key'] = 'value'
    
  2. Use the update() method

     my_dict = {}
     my_dict.update({'key': 'value'})
    

Origin:
https://stackoverflow.com/a/68999475/1645289

Dictionary Find

get:

dict = {'Name': 'Runoob', 'Age': 27}
print "Value : %s" %  dict.get('Age')
print "Value : %s" %  dict.get('Sex', "Not Available")

output:

Value : 27
Value : Not Available

Origin:
https://www.runoob.com/python/att-dictionary-get.html

Dictionary Remove

del:

test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21}
del test_dict['Mani']
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

remove item while iterate dictionary:
use for key in list(dict_2.keys()) intead of for key in dict_2.keys()

for key in list(dict_2.keys()):
    if dict_1.get(key, "null") != 'null':
        del dict_2[key]

otherwise would get error:

python 3 dictionary changed size during iteration

Environment Configuration

How to switch between python 2.7 and python 3

No need for “tricks”. Python 3.3 comes with PyLauncher “py.exe”, installs it in the path, and registers it as the “.py” extension handler. With it, a special comment at the top of a script tells the launcher which version of Python to run:

#!python2
print "hello"

Or

#!python3
print("hello")

From the command line:

Py -3 hello.py

Or

Py -2 hello.py

Reference:
http://docs.python.org/3/using/windows.html
How to switch between python 2.7 to python 3 from command line?
https://stackoverflow.com/a/18059129/1645289

Why Microsoft Store would be open when type python in command line

Open Settings of Windows, search App execution aliases, then disable App Installer.

Reference:
Typing “python” on Windows 10 (version 1903) command prompt opens Microsoft store
https://superuser.com/questions/1437590/typing-python-on-windows-10-version-1903-command-prompt-opens-microsoft-stor

Source files

What does if name == “main”: do?
if __name__ == "__main__":
    print("m1")
print("t2")

Origin:
https://stackoverflow.com/a/419986/1645289


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