2018년 7월 13일 금요일

python cookbook Strings and Text

String

2.1. Splitting Strings on Any of Multiple Delimiters
>>> line = 'asdf fjdk; afed, fjek,asdf,       fo'
>>> import re
>>> re.split(r'[;,\s]\s*', line)
['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'fo']

>>> files = re.split(r'(;|,|\s)\s*', line)
>>> files
['asdf', ' ', 'fjdk', ';', 'afed', ',', 'fjek', ',', 'asdf', ',', 'fo']
>>> values = files[::2]
>>> values
['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'fo']
>>> delimiters = files[1::2]
>>> delimiters
[' ', ';', ',', ',', ',']
>>> ''.join(v+d for v,d in zip(values, delimiters))
'asdf fjdk;afed,fjek,asdf,'

>>> re.split(r'(?:,|;|\s)\s*',line)
['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'fo']


2.2 Matching Text at the Start or End of a String
>>> filename = 'peter.txt'
>>> filename.endswith('.txt')
True
>>> filename.startswith('peter')
True

>>> choices = ['http:', 'ftp:']
>>> url = 'http://www.python.org'
>>> url.startswith(tuple(choices))
>>> re.match('http:|https:|ftp', url)
<_sre.SRE_Match object; span=(0, 5), match='http:'>

2.3 Matching Strings Using Shell Wildcard Patterns
>>> from fnmatch import fnmatch, fnmatchcase
>>> names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py']
>>> [name for name in names if fnmatch(name, 'Dat*.csv')]
['Dat1.csv', 'Dat2.csv']

>>> fnmatchcase('foo.txt.','*TXT')
False


2.4. Matching and Searching for Text Patterns
>>> from fnmatch import fnmatch, fnmatchcase
>>> names = ['Dat1.csv', 'Dat2.csv', 'config.ini', 'foo.py']
>>> [name for name in names if fnmatch(name, 'Dat*.csv')]
['Dat1.csv', 'Dat2.csv']

>>> fnmatchcase('foo.txt.','*TXT')
False

댓글 없음 :

댓글 쓰기