码迷,mamicode.com
首页 > 编程语言 > 详细

python cookbook 字符串和文本

时间:2017-03-23 23:47:39      阅读:242      评论:0      收藏:0      [点我收藏+]

标签:调用   ext   imp   log   match   upper   bsp   count   元组   

使用多个界定符分隔字符串

  import re
  line = ‘asdf fjdk; afed, fjek,asdf, foo‘
  print(re.split(r‘[;,\s]\s*‘, line))
  print(re.split(r‘(;|,|\s)\s*‘, line))     #加括号表示捕获分组,这样匹配的结果也显示在列表中

匹配开头或结尾

  url = ‘http://www.python.org‘
  print(url.startswith((‘http‘, ‘https‘, ‘ftp‘)))  # 如果匹配多个一定是元组,list和set必须先调用tuple()转成元祖
  import re
  print(re.match(‘http:|https:|ftp:‘, url))    #正则也可以

使用Shell中的通配符匹配

  from fnmatch import fnmatch, fnmatchcase
  print(‘foo.txt‘, ‘*.txt‘)
  print(‘foo.txt‘, ‘?oo.txt‘)
  print(‘Dat45‘, ‘Dat[0-9]*‘)
  names = [‘Dat1.csv‘, ‘Dat2.csv‘, ‘config.ini‘, ‘foo.py‘]
  print([name for name in names if fnmatch(name, ‘Dat*.csv‘)])

忽略大小写匹配和替换

  import re
  text = ‘UPPER PYTHON, lower python, Mixed Python‘
  print(re.findall(‘python‘, text, re.IGNORECASE))
  print(re.findall(‘python‘, text))
  print(re.sub(‘python‘, ‘java‘, text, count=100, flags=re.IGNORECASE))
  

 

python cookbook 字符串和文本

标签:调用   ext   imp   log   match   upper   bsp   count   元组   

原文地址:http://www.cnblogs.com/badboyf/p/6607853.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!