python常用语句
1、创建文件时,在文件头部自动加入信息
引用自:https://blog.csdn.net/kaikai136412162/article/details/80843579
打开File -> Settings -> Editor -> File and Code Templates -> Python Script
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# @Software : ${PRODUCT_NAME}
# @CreateTime: ${YEAR}-${MONTH}-${DAY} ${HOUR}:${MINUTE}
# @Author : ${USER}
# @File : ${NAME}
import sys, time, pprint, json, re
def getCurrentTime():
return time.strftime('%Y-%m-%d %H:%M:%S')
def showMessage(lineno=sys._getframe().f_lineno, filename=__file__, *args):
try:
strLine = '"{}:{}"'.format(filename, lineno)
strMessage = ''
for strTxt in args:
strMessage += str(strTxt)
strPrint = '{} {}, {}'.format(getCurrentTime(), strLine, strMessage)
print(strPrint)
except Exception as e:
strPrint = '{} {}, {}'.format(getCurrentTime(), sys._getframe().f_lineno, str(e))
print('\n{}'.format(strPrint))
finally:
print()
def main():
print("in main...")
print("-=" * 90)
showMessage()
if __name__ == '__main__':
print("in startMain...")
print("-=" * 90)
main()
1、打印行号,
ref,https://blog.csdn.net/JohinieLi/article/details/80141669
print(__file__)
import sys
print('\nLine_{:0>5d} in {}'.format(sys._getframe().f_lineno, __file__))
x = 1234.56789
# Two decimal places of accuracy
In [2]: format(x, '0.2f') #无空格,小数保留2位
Out[2]: '1234.57'
# Right justified in 10 chars, one-digit accuracy
In [3]: format(x, '>10.1f') #数字输出靠右,总计长度为10,小数保留1位
Out[3]: ' 1234.6'
# Left justified
In [4]: format(x, '<10.1f') #数字输出靠左,总计长度为10,小数保留1位
Out[4]: '1234.6 '
# Centered
In [5]: format(x, '^10.2f') #数字输出靠中,小数保留2位
Out[5]: ' 1234.57 '
# Inclusion of thousands separator
In [6]: format(x, ',') #指定逗号位数字的千分位分隔符
Out[6]: '1,234.56789'
In [7]: format(x, '0,.1f') #无占位输出,用逗号作为分隔符,保留1位小数
Out[7]: '1,234.6'
2、打印日期
import datetime
print(datetime.datetime.now()) # type = datetime.datetime
import time
print(time.strftime('%Y-%m-%d %H:%M:%S'))
print(time.strftime('%Y_%m_%d_%H_%M_%S_.txt'))
3、中英文对齐
https://blog.csdn.net/lv1224/article/details/77678631 推荐使用
https://blog.csdn.net/Excaliburrr/article/details/76794451
4、python3.6 input() to byte
参考 Python3中内置类型bytes和str用法及byte和string之间各种编码转换
myInput = input('>>>') # 开始接收输入,无论输入什么,type(myInput) 恒等于 str
myInputList = myInput.split(' ') # 以空格分割输入串
iMyInputList = [int(strSub) for strSub in myInputList] # Convert str to int
sendByte = bytes(iMyInputList) # Convert intArray to bytes
5、爬虫时过滤表头行
position()>1
如:
trTags = response.xpath("//div[@id='container']/table//table[3]//tr[position()>1])
openData = trTags[0].xpath("./td[3]/text()").get()
6、正则提取小区名
import re
searchResult = re.match(r'(.*?)[A-Z\d+].*', oldName)
if searchResult:
newName = searchResult.group(1)
print(oldName, newName)
7、字典实现switch-case
# 地市区号链接 http://quhao.tianqi.com/shengfen-anhui/
def getLocalNet(localNet):
return {
"550": "滁州",
"551": "合肥",
"552": "蚌埠",
"553": "芜湖",
"554": "淮南",
"555": "马鞍山",
"556": "安庆",
"557": "宿州",
"558": "阜阳",
"559": "黄山",
"560": "亳州",
"561": "淮北",
"562": "铜陵",
"563": "宣城",
"564": "六安",
"565": "巢湖",
"566": "池州",
}.get(localNet, 'error') # 'error'为默认返回值,可自设置
cityName = getLocalNet('558') # 阜阳
8、由字符串 转为 属性 的 2 种方法
参考 Python中getattr、get、__getattr__和__getattribute__的区别
# cv is import cv2 as cv
# so cv is class
# and than
lineType = 'LINE_AA'
lineTypeAttr = getattr(cv, lineType)
lineTypeAttr = cv.__getattribute__(lineType) # 仅适用于 新式类