Learning Python(3)
handle string
#大写首字符>>> 'abc def'.capitalize()'Abc def'>>> 'ABC DEF'.lower()'abc def'>>> 'abc def'.title()'Abc Def'#是否是字母+数字组合>>> 'abc123'.isalnum()True#是否是数字>>> 'abc'.isdigit()False>>> 'abcde'.startswith('ab')True>>> 'abcde'.endswith('de')True#指定字串第一次出现的索引>>> 'abcde'.index('bc')1>>> 'abcde'.replace('bc','fg')'afgde'>>> '1,2,3,4,5,6,7'.split(',',3)['1', '2', '3', '4,5,6,7']>>> '1,2,3,4,5,6,7'.rsplit(',',3)['1,2,3,4', '5', '6', '7']
name='jilu'age=27info='{0} is {1} years old'.format(name,age)print(info)
import rep=re.compile('"(https?://.*?)"',re.IGNORECASE) #complie()方法里面第一个参数为正则式with open('HackerNews.htm',encoding='UTF-8') as file_object: doc=file_object.read()for i in p.findall(doc): #findall()方法接受str完成匹配 print(i)
from collections import *nt=namedtuple('nt','name age loc')nt1=nt('jilu','27','Beijing')print(nt1)#nt(name='jilu', age='27', loc='Beijing')
from collections import *doc='A wiki enables communities of editors and contributors to write documents collaboratively. ' \ 'All that people require to contribute is a computer, Internet access, a web browser and a basic understanding of a simple markup language (e.g., HTML). ' \ 'A single page in a wiki website is referred to as a "wiki page", while the entire collection of pages, which are usually well-interconnected by hyperlinks, is "the wiki". ' \ 'A wiki is essentially a database for creating, browsing, and searching through information. A wiki allows non-linear, evolving, complex and networked text, while also allowing for editor argument, debate and interaction regarding the content and formatting.' \ 'A defining characteristic of wiki technology is the ease with which pages can be created and updated. Generally, there is no review by a moderator or gatekeeper before modifications are accepted and thus lead to changes on the website. ' \ 'Many wikis are open to alteration by the general public without requiring registration of user accounts.'world_list=doc.split()print(Counter(world_list))#Counter({'and': 8, 'a': 8, 'is': 6, 'wiki': 5, 'of': 5, 'to': 5, 'the': 5, 'A': 4...})
from collections import *from collections import *cl = defaultdict(list)print(cl['key'])print(cl)cl['key'].append(1)cl['key'].append(2)cl['key'].append(3)cl['key1'].append(1)print(cl)#[]#defaultdict(<class 'list'>, {'key': []})#defaultdict(<class 'list'>, {'key': [1, 2, 3], 'key1': [1]})
name='xianbei'age=24print( '{0} is {1} years old'.format(name,age))print( '{first} is {second} years old'.format(first=name,second=age))print( '{0:.3} is a decimal.'.format(1/3.0) #控制小数点位数,.3是三位小数)
print( '{:<10}{:10}'.format(1,2))#排版控制:{:[对齐方式<^>][宽度]}#1 2
>>> import math>>> for i in [-3.5,-2.8,-0.2,0,0.2,1.5,2.8,3.5]:... print(i,int(i),math.trunc(i),math.floor(i),math.ceil(i))...-3.5 -3 -3 -4 -3-2.8 -2 -2 -3 -2-0.2 0 0 -1 00 0 0 0 00.2 0 0 0 11.5 1 1 1 22.8 2 2 2 33.5 3 3 3 4
>>> import math>>> math.fabs(-1.1)1.1>>> math.copysign(8.6,-2)-8.6
>>> import math>>> values=[value*0.01 for value in range(10)]>>> math.fsum(values)0.45>>> for i in range(8):... print(i,math.factorial(i))...0 11 12 23 64 245 1206 7207 5040
>>> math.pow(2,3)8.0>>> math.log(8,2)3.0>>> math.log(8) #底为e2.0794415416798357>>> math.log(8,math.e) #how to use e2.0794415416798357>>> math.exp(2)7.38905609893065
>>> import time>>> time.time()1517275993.898113>>> time.ctime()'Tue Jan 30 09:33:18 2018'>>> time.gmtime()time.struct_time(tm_year=2018, tm_mon=1, tm_mday=30, tm_hour=1, tm_min=34, tm_sec=20, tm_wday=1, tm_yday=30, tm_isdst=0)
>>> import random>>> random.seed(5)>>> for i in range(5):... print(random.random()) #random.randint();random.randrange()...0.201366651268153780.9377444827722460.70406338900229340.86351108371280080.3503527767880694
>>> import random>>> a=[i for i in range(10)]>>> for x in range(5):... random.shuffle(a)... print(a)...[9, 8, 0, 4, 7, 5, 2, 1, 3, 6][1, 5, 2, 6, 0, 7, 8, 3, 4, 9][1, 8, 2, 3, 5, 7, 6, 0, 9, 4][5, 0, 1, 9, 8, 7, 4, 6, 3, 2][6, 1, 7, 4, 3, 5, 0, 8, 2, 9]>>> for x in range(5):... print(random.choice(a))...00624>>> for x in range(5):... print(random.sample(a,3))...[7, 6, 0][5, 6, 3][8, 7, 6][3, 5, 6][0, 8, 6]
import gzipwith gzip.open('abc.log.gz','w') as gz: for x in ['a','b','c']: gz.write(bytes(x,'UTF-8'))
import tracebackdef produce_exception(): raise Exception('test')try: produce_exception()except Exception as e: print(traceback.format_exc())#####################################Traceback (most recent call last): File "D:/ITWorkSpace/MyPy/mypy.py", line 6, in <module> produce_exception() File "D:/ITWorkSpace/MyPy/mypy.py", line 3, in produce_exception raise Exception('test')Exception: test