首页 > 解决方案 > 如何在我的 doctest 中只为完整的单词匹配返回 TRUE?

问题描述

TRUE如果物种名称以开头,我有一个 doctest 要返回,但如果给定的物种名称包含拼写错误(例如)quercus,它也会返回。我如何确保它不仅以该物种名称开头并且仅与完整单词匹配?TRUEquercussTRUE

def is_an_oak(name):
    """ Returns True if name is starts with 'quercus'""" 
    return name.lower().startswith('quercus')

我尝试在单词后留一个空格,但在脚本中进一步使用该函数时它省略了结果:

def is_an_oak(name):
    """ Returns True if name is starts with 'quercus'""" 
    return name.lower().startswith('quercus ')

标签: pythondoctest

解决方案


为了得到这个词;

import re

def is_an_oak(name):
    """ Returns Name if name is 'quercus'""" 
    return re.match("^[qQ]uercus*",name).string

为了获得 TRUE/FALSE

 import re

 def is_an_oak(name):
     """ Returns True if name is 'quercus'""" 
     if re.match("^[qQ]uercus*",name):
         return True
     else:
         return False

推荐阅读