[关闭]
@ExcitedSpider 2018-01-30T10:00:52.000000Z 字数 4270 阅读 1046

Learning Python(3)

handle string

  1. #大写首字符
  2. >>> 'abc def'.capitalize()
  3. 'Abc def'
  4. >>> 'ABC DEF'.lower()
  5. 'abc def'
  6. >>> 'abc def'.title()
  7. 'Abc Def'
  8. #是否是字母+数字组合
  9. >>> 'abc123'.isalnum()
  10. True
  11. #是否是数字
  12. >>> 'abc'.isdigit()
  13. False
  14. >>> 'abcde'.startswith('ab')
  15. True
  16. >>> 'abcde'.endswith('de')
  17. True
  18. #指定字串第一次出现的索引
  19. >>> 'abcde'.index('bc')
  20. 1
  21. >>> 'abcde'.replace('bc','fg')
  22. 'afgde'
  23. >>> '1,2,3,4,5,6,7'.split(',',3)
  24. ['1', '2', '3', '4,5,6,7']
  25. >>> '1,2,3,4,5,6,7'.rsplit(',',3)
  26. ['1,2,3,4', '5', '6', '7']
  1. name='jilu'
  2. age=27
  3. info='{0} is {1} years old'.format(name,age)
  4. print(info)
  1. import re
  2. p=re.compile('"(https?://.*?)"',re.IGNORECASE) #complie()方法里面第一个参数为正则式
  3. with open('HackerNews.htm',encoding='UTF-8') as file_object:
  4. doc=file_object.read()
  5. for i in p.findall(doc): #findall()方法接受str完成匹配
  6. print(i)
  1. from collections import *
  2. nt=namedtuple('nt','name age loc')
  3. nt1=nt('jilu','27','Beijing')
  4. print(nt1)
  5. #nt(name='jilu', age='27', loc='Beijing')
  1. from collections import *
  2. doc='A wiki enables communities of editors and contributors to write documents collaboratively. ' \
  3. '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). ' \
  4. '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". ' \
  5. '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.' \
  6. '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. ' \
  7. 'Many wikis are open to alteration by the general public without requiring registration of user accounts.'
  8. world_list=doc.split()
  9. print(Counter(world_list))
  10. #Counter({'and': 8, 'a': 8, 'is': 6, 'wiki': 5, 'of': 5, 'to': 5, 'the': 5, 'A': 4...})
  1. from collections import *
  2. from collections import *
  3. cl = defaultdict(list)
  4. print(cl['key'])
  5. print(cl)
  6. cl['key'].append(1)
  7. cl['key'].append(2)
  8. cl['key'].append(3)
  9. cl['key1'].append(1)
  10. print(cl)
  11. #[]
  12. #defaultdict(<class 'list'>, {'key': []})
  13. #defaultdict(<class 'list'>, {'key': [1, 2, 3], 'key1': [1]})
  1. name='xianbei'
  2. age=24
  3. print(
  4. '{0} is {1} years old'.format(name,age)
  5. )
  6. print(
  7. '{first} is {second} years old'.format(first=name,second=age)
  8. )
  9. print(
  10. '{0:.3} is a decimal.'.format(1/3.0) #控制小数点位数,.3是三位小数
  11. )
  1. print(
  2. '{:<10}{:10}'.format(1,2)
  3. )
  4. #排版控制:{:[对齐方式<^>][宽度]}
  5. #1 2
  1. >>> import math
  2. >>> for i in [-3.5,-2.8,-0.2,0,0.2,1.5,2.8,3.5]:
  3. ... print(i,int(i),math.trunc(i),math.floor(i),math.ceil(i))
  4. ...
  5. -3.5 -3 -3 -4 -3
  6. -2.8 -2 -2 -3 -2
  7. -0.2 0 0 -1 0
  8. 0 0 0 0 0
  9. 0.2 0 0 0 1
  10. 1.5 1 1 1 2
  11. 2.8 2 2 2 3
  12. 3.5 3 3 3 4
  1. >>> import math
  2. >>> math.fabs(-1.1)
  3. 1.1
  4. >>> math.copysign(8.6,-2)
  5. -8.6
  1. >>> import math
  2. >>> values=[value*0.01 for value in range(10)]
  3. >>> math.fsum(values)
  4. 0.45
  5. >>> for i in range(8):
  6. ... print(i,math.factorial(i))
  7. ...
  8. 0 1
  9. 1 1
  10. 2 2
  11. 3 6
  12. 4 24
  13. 5 120
  14. 6 720
  15. 7 5040
  1. >>> math.pow(2,3)
  2. 8.0
  3. >>> math.log(8,2)
  4. 3.0
  5. >>> math.log(8) #底为e
  6. 2.0794415416798357
  7. >>> math.log(8,math.e) #how to use e
  8. 2.0794415416798357
  9. >>> math.exp(2)
  10. 7.38905609893065
  1. >>> import time
  2. >>> time.time()
  3. 1517275993.898113
  4. >>> time.ctime()
  5. 'Tue Jan 30 09:33:18 2018'
  6. >>> time.gmtime()
  7. 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)
  1. >>> import random
  2. >>> random.seed(5)
  3. >>> for i in range(5):
  4. ... print(random.random()) #random.randint();random.randrange()
  5. ...
  6. 0.20136665126815378
  7. 0.937744482772246
  8. 0.7040633890022934
  9. 0.8635110837128008
  10. 0.3503527767880694
  1. >>> import random
  2. >>> a=[i for i in range(10)]
  3. >>> for x in range(5):
  4. ... random.shuffle(a)
  5. ... print(a)
  6. ...
  7. [9, 8, 0, 4, 7, 5, 2, 1, 3, 6]
  8. [1, 5, 2, 6, 0, 7, 8, 3, 4, 9]
  9. [1, 8, 2, 3, 5, 7, 6, 0, 9, 4]
  10. [5, 0, 1, 9, 8, 7, 4, 6, 3, 2]
  11. [6, 1, 7, 4, 3, 5, 0, 8, 2, 9]
  12. >>> for x in range(5):
  13. ... print(random.choice(a))
  14. ...
  15. 0
  16. 0
  17. 6
  18. 2
  19. 4
  20. >>> for x in range(5):
  21. ... print(random.sample(a,3))
  22. ...
  23. [7, 6, 0]
  24. [5, 6, 3]
  25. [8, 7, 6]
  26. [3, 5, 6]
  27. [0, 8, 6]
  1. import gzip
  2. with gzip.open('abc.log.gz','w') as gz:
  3. for x in ['a','b','c']:
  4. gz.write(bytes(x,'UTF-8'))
  1. import traceback
  2. def produce_exception():
  3. raise Exception('test')
  4. try:
  5. produce_exception()
  6. except Exception as e:
  7. print(traceback.format_exc())
  8. #####################################
  9. Traceback (most recent call last):
  10. File "D:/ITWorkSpace/MyPy/mypy.py", line 6, in <module>
  11. produce_exception()
  12. File "D:/ITWorkSpace/MyPy/mypy.py", line 3, in produce_exception
  13. raise Exception('test')
  14. Exception: test
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注