This article list some python tricks you may use in python development. It is very useful for you to understand python coding.
1. Use Lambda To Mimic Output Method.
# import sys module. >>> import sys >>> # create a lambda expression. The lambda expression will print a string in standard output. >>> lambda_print_func = lambda *args: sys.stdout.write(",".join(map(str, args))) >>> # invoke above lambda expression. >>> lambda_print_func("hello", 99, "word", 1000) hello,99,word,1000
2. Implement Switch Case Statement.
>>> # define switch function ... def switch_func(key): ... # the switch function will return value from it's default system dictionary object by key. ... return switch_func._system_dict.get(key, None) ... >>> # initialize the switch_func system dictionary object. ... switch_func._system_dict = {"java":9, "python":10, "jquery":16} >>> >>> # print different switch_func value by key. ... print(switch_func("default")) None >>> >>> print(switch_func("python")) 10
3. Create Dictionary Object From Two Tuple.
>>> t1 = (1, 2, 3) >>> >>> print(t1) (1, 2, 3) >>> >>> t2 = (10, 20, 30) >>> >>> print(t2) (10, 20, 30) >>> >>> t3 = zip(t1, t2) >>> >>> print(t3) <zip object at 0x7f7322ee3388> >>> >>> d = dict(t3) >>> >>> print(d) {1: 10, 2: 20, 3: 30} >>>
4. Create Python List Use itertools Module.
>>> import itertools >>> >>> test = [['java', 'python'], ['ford', 'bmw'], [25, 35]] >>> >>> it = itertools.chain.from_iterable(test) >>> >>> it <itertools.chain object at 0x7f7322ee0d30> >>> >>> list = list(it) >>> >>> list ['java', 'python', 'ford', 'bmw', 25, 35]
5. String startswith & endswith Method.
Method startswith & endswith are case sensitive.
>>> str_1 = "hello python world" >>> >>> str_1.startswith(('hello','python')) True >>> str_1.endswith(('hello','python')) False >>> str_1.endswith(('world','python')) True >>> str_1.endswith(('World','python')) False
6. Exchange Two Variable Value.
>>> x, y ='python', 10 >>> >>> print(x, y) python 10 >>> >>> y, x = x, y >>> >>> print(x, y) 10 python
7. Find The Smallest Number In ABC.
>>> def smallest_value(a, b, c): ... return a if a<b and a<c else (b if b<a and b<c else c) ... >>> print(smallest_value(1, 0, 1)) 0 >>> print(smallest_value(1, 0, 9)) 0 >>> print(smallest_value(1, 2, 9)) 1
8. List Comprehension.
>>> list = [m**2 if m>5 else m**4 for m in range(10)] >>> >>> list [0, 1, 16, 81, 256, 625, 36, 49, 64, 81]
9. Multiple Line String.
>>> multistr = "select * from account \ ... where username < 'tom'" >>> print(multistr) select * from account where username < 'tom' >>> >>> >>> multistr = """select * from account ... where username = 'tom'""" >>> print(multistr) select * from account where username = 'tom' >>> >>> >>> multistr = ("select * from account" ... "where username < 'tom'" ... "order by salary") >>> print(multistr) select * from accountwhere username < 'tom'order by salary >>>
10. Extract List Element Into Variables.
The number of variables should be exactly the same as the length of the list.
>>> list = [1, 'python', 3] >>> >>> list [1, 'python', 3] >>> >>> a, b, c = list >>> >>> a 1 >>> >>> b 'python' >>> >>> c 3
11. Print Imported Module Absolute Path.
>>> import os >>> import socket >>> >>> print(os) <module 'os' from '/home/zhaosong/anaconda3/lib/python3.7/os.py'> >>> >>> print(socket) <module 'socket' from '/home/zhaosong/anaconda3/lib/python3.7/socket.py'>
12. The _ Operator In Interactive Environment.
In the python interactive console, whether we test an expression or call a method, the result is assigned to a temporary variable “_”, please see below example.
>>> str(10) '10' >>> _ '10'
13. Dictionary / List / Set Derivation.
>>> test_dict = {i: i * i for i in range(10)} >>> >>> test_dict {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} >>> >>> test_list = [i * 2 for i in range(10)] >>> >>> test_list [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] >>> >>> test_set = {i * 2 for i in range(10)} >>> >>> test_set {0, 2, 4, 6, 8, 10, 12, 14, 16, 18}
14. Debug Python Script.
Use pdb module to set breakpoint.
>>> import pdb >>> >>> pdb.set_trace() --Return-- > <stdin>(1)<module>()->None (Pdb)
15. Share Files Through HTTP Web Server.
Python allows you to start a HTTP web server to share files from the root directory.
$ python -m http.server Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
16. Use dir() Method To Display All Methods And Attributes Of Python Object.
We can see the list object below has methods that we are familiar with : append, clear, insert etc.
>>> list = ['java', 'python'] >>> >>> print(dir(list)) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
17. Detect Python Version In Runtime.
>>> import sys >>> py_version = hasattr(sys, "hexversion") >>> py_version True >>> py_version = sys.version_info >>> py_version sys.version_info(major=3, minor=6, micro=5, releaselevel='final', serial=0) >>> py_version = sys.version >>> py_version '3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37) \n[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]' >>>
18. Concat Multiple String.
>>> str_list = ["python", "is", "a", "good", "programming", "language"] >>> >>> str_list ['python', 'is', 'a', 'good', 'programming', 'language'] >>> >>> str_list_1 = " , ".join(str_list) >>> >>> str_list_1 'python , is , a , good , programming , language'
19. Simplify If Statement.
If you need to check multiple conditions in if statement, use list instead of multiple equal.
Use :
if x in [1, 2, 3]:
to replace:
if x==1 or x==2 or x==3
20. Flip String Or List.
>>> str_1 = 'python' >>> for i, value in enumerate(str_1): ... print(i, ':', value) ... 0 : p 1 : y 2 : t 3 : h 4 : o 5 : n
21. Define Enumerator.
>>> class colors: ... red, blue, green = range(3) ... >>> colors.red 0 >>> >>> colors.blue 1 >>> >>> colors.green 2
22. Return Multiple Value From Function.
>>> def get_int(): ... ... return 1, 2, 3 ... >>> x, y, z = get_int() >>> >>> x, y, z (1, 2, 3)
23. Use * Operator To Unpack Function Parameters.
>>> def test_func(a, b, c): ... print(a) ... print(b) ... print(c) ... >>> test_dict = {'a':1, 'b':2, 'c':3} >>> >>> test_list = ['java', 'python', 'c++'] >>> >>> test_func(*test_dict) a b c >>> >>> test_func(**test_dict) 1 2 3 >>> >>> test_func(*test_list) java python c++
24. Use Dictionary To Store Expressions.
>>> dict_lambda = { ... "add": lambda x, y: x + y, ... "multiple": lambda x, y: x * y ... } >>> >>> dict_lambda["add"](1, 1) 2 >>> >>> dict_lambda["multiple"](9, 3) 27
25. Check An Object Used Memory Size.
>>> import sys >>> >>> str_1 = 'python' >>> >>> str_size = sys.getsizeof(str_1) >>> >>> str_size 55