Python Challenge lv3: re

Python Challenge lv3: re

  题目链接: http://www.pythonchallenge.com/pc/def/equality.html

  One small letter, surrounded by EXACTLY three big bodyguards on each of its sides.  何为big bodyguards? 我估计是大写字母,即要求找到由三个大写字母包围着的小写字母。事实上,题目要求的确如此。不过我在一开始的时候走了弯路:我把连续的七个字母全部都打印出来了(左边三个大写字母,中间一个小写字母,右边三个大写字母),费了半天才搞明白原来要求的只是中间的小写字母。
  另外注意EXACTLY 这个词,即“当且仅当”左右两边均为“三”个大写字母的pattern才算。

  代码到也简单:

import  re

if   __name__   ==   ' __main__ ' :    
    finpath 
=   ' fin.txt '
    with open(finpath) as fin:
        
#  translate text into a single string
        text  =   '' .join([line.rstrip()  for  line  in  fin.read()])
        pattern 
=  re.compile(r ' [^A-Z][A-Z]{3}([a-z])[A-Z]{3}[^A-Z] ' )
        
print ( '' .join(pattern.findall(text)))

程序输出:linkedlist

参考答案

你可能感兴趣的:(Python Challenge lv3: re)