2015年12月26日土曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Automate the Boring Stuff with Python: Practical Programming for Total Beginners (Al Sweigart (著)、No Starch Press)のPart 2.(Automating Tasks)、Chapter 7.(Pattern Matching with Regular Expressions)、Practice Projects(Regex Version of strip())を解いてみる。

Practice Projects(Regex Version of strip())

コード(Emacs)

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import re

def strip(s, chars='\\s'):
    return re.search(r'({0})*(.*?)({0})*$'.format(chars), s).group(2)

pythons = ['python', '     python', 'python     ', '     python          ',
           'p y thon']
for s in pythons:
    print("'{0}': '{1}'".format(s, strip(s)))

for s in pythons:
    print("'{0}': '{1}'".format(s, strip(s, "ab")))

pythons = ['python', 'ababpython', 'pythonabab', 'abpythona', 'abpythonabpythnonab']
for s in pythons:
    print("'{0}': '{1}'".format(s, strip(s, "ab")))

入出力結果(Terminal, IPython)

$ ./sample2.py
'python': 'python'
'     python': 'python'
'python     ': 'python'
'     python          ': 'python'
'p y thon': 'p y thon'
'python': 'python'
'     python': '     python'
'python     ': 'python     '
'     python          ': '     python          '
'p y thon': 'p y thon'
'python': 'python'
'ababpython': 'python'
'pythonabab': 'python'
'abpythona': 'pythona'
'abpythonabpythnonab': 'pythonabpythnon'
$

0 コメント:

コメントを投稿

Comments on Google+: