30个你想打包带走的Python技巧(下)
你可以在 Python 中将多个比较运算符链接到一起,如此就可以创建更易读、更简洁的代码: 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. 添加颜色你可以通过 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. 日期的处理python-dateutil 模块作为标准日期模块的补充,提供了非常强大的扩展,你可以通过如下命令安装: pip3 install python-dateutil 你可以利用该库完成很多神奇的操作。在此我只举一个例子:模糊分析日志文件中的日期: 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 你只需记住:当遇到常规 Python 日期时间功能无法解决的问题时,就可以考虑 python-dateutil ! 29.整数除法在 Python 2 中,除法运算符(/)默认为整数除法,除非其中一个操作数是浮点数。因此,你可以这么写: # Python 2 5 / 2 = 2 5 / 2.0 = 2.5 在 Python 3 中,除法运算符(/)默认为浮点除法,而整数除法的运算符为 //。因此,你需要这么写: Python 3 5 / 2 = 2.5 5 // 2 = 2 这项变更背后的动机,请参阅 PEP-0238(https://www.python.org/dev/peps/pep-0238/)。 30. 通过chardet 来检测字符集你可以使用 chardet 模块来检测文件的字符集。在分析大量随机文本时,这个模块十分实用。安装方法如下: pip install chardet 安装完成后,你就可以使用命令行工具 chardetect 了,使用方法如下: chardetect somefile.txt somefile.txt: ascii with confidence 1.0 你也可以在编程中使用该库,完整的文档请点击这里(https://chardet.readthedocs.io/en/latest/usage.html)。 原文链接:https://towardsdatascience.com/30-python-best-practices-tips-and-tricks-caefb9f8c5f5 (编辑:应用网_阳江站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |