python cookbook阅读之——2.字符串和文本

2.1 字符串对象的split只能处理简单情况,而且不支持多个分隔符,对分隔符周围可能存在的空格也无能为力。所以需要灵活功能时,可以使用re.split()

>>> import re
>>> line = '123,wfsd; fdfsf vb       foo'
>>> re.split(r'[;,\s]\s*', line)
['123', 'wfsd', 'fdfsf', 'vb', 'foo']

2.2 在字符串的开头结尾处做文本匹配 str.startswith(),   str.endswith()

>>> filename = 'http://span.txt'
>>> filename.startswith("http")
True

2.3 fnmatch,fnmatchcase。在linux下和windows下fnmatch大小写的处理不一样,推荐使用fnmatchcase

>>> from fnmatch import fnmatch,fnmatchcase
>>> fnmatch('foo.txt', '*.TXT')  #在windows下
True
>>> fnmatch('foo.txt', '*.TXT')  #在linux下
False
>>> fnmatchcase('foo.txt', '*.TXT')  
False

2.4 不区分大小写的方式对文本做查找和替换 re.IGNORECASE

>>> text = "PYThon 1, python 2, Python 3, PYTHON 4"
>>> re.findall('python', text, flags=re.IGNORECASE)
['PYThon', 'python', 'Python', 'PYTHON']

2.5 字符串拼接, join()

>>> parts = ['I', 'am', 'a', 'girl']
>>> ' '.join(parts)
'I am a girl'
>>> ','.join(parts)
'I,am,a,girl'
>>> ''.join(parts)
'Iamagirl'

2.5 字符串中的变量名做插值处理

>>> s = '{a} am a {b}'
>>> s.format(a="I", b="girl")
'I am a girl'

 

你可能感兴趣的:(python)