#python
list.sort() 是原地排序,且永远返回 Nonepython
# wrong
listA = list(A).sort() # listA == None
# right
listA = list(A)
listA.sort()
# or
listA = sorted(list(A))
#python
http://blog.jobbole.com/42706/
Python 新手常犯错误(第一部分)
TL;DR
不要用一个可变的值作为默认值
正确做法
http://blog.jobbole.com/42706/
Python 新手常犯错误(第一部分)
TL;DR
不要用一个可变的值作为默认值
>>> def foo(numbers=[]):
... numbers.append(9)
... return numbers
>>> foo()
[9]
>>> foo()
[9, 9]
>>> foo()
[9, 9, 9]
正确做法
def foo(numbers=None):
if numbers is None:
numbers = []
numbers.append(9)
return numbers
#python
使用crontab运行python时日志乱码
解决方案
在cron中设置
更多信息:https://stackoverflow.com/questions/40718088/encoding-issue-when-running-python-script-from-crontab
使用crontab运行python时日志乱码
解决方案
在cron中设置
LANG 变量* * * * * LANG=en_US.UTF-8 python3 main.py >> log.log
更多信息:https://stackoverflow.com/questions/40718088/encoding-issue-when-running-python-script-from-crontab
Stack Overflow
Encoding issue when running python script from crontab
I am migrating my python scripts from one server to a new docker container. But I am facing a strange issue with encoding, I tried several solutions without success.
If I run the script directly ...
If I run the script directly ...
#python
strip
python的 str.strip([chars]) 和其他语言的 trim 不同, strip 会去除字符串头尾的每个 chars 字符,由于不好解释,请查看以下例子>>>'1122A'.strip('12')
'A' # 删去了字符串头部所有 ‘1’ 和 ‘2’
另外还有只用来去除开头字符的 lstrip 和只用来去除结尾字符的 rstrip
如果只是想要移除字符串头部的指定字符串应该尝试使用其他方法s = 'StringToRemove'
if line.startswith(s):
return line[len(s):]
#python
python 中对 bytes 取反的正确姿势
不进行 & 操作的话位数会太长
https://stackoverflow.com/questions/28361323/python3-byte-level-bit-operations
python 中对 bytes 取反的正确姿势
b = bytes([~ b & 0xFF])
不进行 & 操作的话位数会太长
https://stackoverflow.com/questions/28361323/python3-byte-level-bit-operations