21. Use _ (underscore operator) in an interactive shell
You can get the result of the previous expression through the underscore operator. For example, in IPython, you can do this:
In [1]: 3 * 3
Out[1]: 9In [2]: _ + 3
Out[2]: 12
This can also be used in Python Shell. In addition, in the IPython shell, you can also get the value of the expression In[n] through Out[n]. For example, in the example above, Out[1] will return the number 9.
22. Quickly create a web server
You can quickly start a web service and provide the contents of the current directory:
python3 -m http.server
You can consider this method when you want to share a file with colleagues or test a simple HTML website.
23. Multi-line string
Although you can use triple quotes to enclose multi-line strings in the code, this approach is not ideal. All the content between the triple quotes will become a string, including the format of the code, as shown below.
I prefer another method, which can not only concatenate multiple lines of strings together, but also keep the code clean. The only disadvantage is that you need to specify the newline character explicitly.
s1 = """Multi line strings can be put
between triple quotes. It's not ideal
when formatting your code though"""
print (s1)
# Multi line strings can be put
# between triple quotes. It's not ideal
# when formatting your code though
s2 = ("You can also concatenate multiple\n" +
"strings this way, but you'll have to\n"
"explicitly put in the newlines")
print(s2)
# You can also concatenate multiple
# strings this way, but you'll have to
# explicitly put in the newlines
24. Ternary operator in conditional assignment
This method can make the code more concise, while ensuring the readability of the code:
[on_true] if [expression] else [on_false]
示例如下:
x = "Success!" if (y == 2) else "Failed!"
25. Count the occurrences of elements
You can use the Counter in the collection library to get the number of occurrences of all unique elements in the list. Counter will return a dictionary:
from collections import Counter
mylist = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6]
c = Counter(mylist)
print(c)
# Counter({1: 2, 2: 1, 3: 1, 4: 1, 5: 3, 6: 2})
# And it works on strings too:
print(Counter("aaaaabbbbbccccc"))
# Counter({'a': 5, 'b': 5, 'c': 5})
26. Links to comparison operators
You can link multiple comparison operators together in Python to create more readable and concise code:
x = 10
# Instead of:
if x > 5 and x < 15:
print("Yes")
# yes
# You can also write:
if 5 < x < 15:
print("Yes")
# Yes
27. Add color
You can set the display color of the terminal through Colorama:
from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')
28. Date processing
As a supplement to the standard date module, the python-dateutil module provides a very powerful extension. You can install it with the following command:
pip3 install python-dateutil
You can use this library to accomplish many magical operations. Here I just give an example: Fuzzy analysis of the date in the log file:
from dateutil.parser import parse
logline = 'INFO 2020-01-01T00:00:01 Happy new year, human.'
timestamp = parse(log_line, fuzzy=True)
print(timestamp)
# 2020-01-01 00:00:01
You only need to remember: when you encounter a problem that the regular Python date and time functions cannot solve, you can consider python-dateutil!
29. Integer Division
In Python 2, the division operator (/) defaults to integer division, unless one of the operands is a floating point number. Therefore, you can write:
# Python 2
5 / 2 = 2
5 / 2.0 = 2.5
在 Python 3 中,除法运算符(/)默认为浮点除法,而整数除法的运算符为 //。因此,你需要这么写:
Python 3
5 / 2 = 2.5
5 // 2 = 2
For the motivation behind this change, please see PEP-0238 (https://www.python.org/dev/peps/pep-0238/).
30. Detect the character set by chardet
You can use the chardet module to detect the character set of the file. This module is very useful when analyzing large amounts of random text. The installation method is as follows:
pip install chardet
After the installation is complete, you can use the command line tool chardetect as follows:
chardetect somefile.txt
somefile.txt: ascii with confidence 1.0