像这样使用regex
:
>>> line = "Student = Small |1-2| Student"
>>> if re.search(r"\bSmall\b",line):
print re.sub("^(\w+)|(\w+)$",lambda x:x.group()+"Short",line)
'StudentShort = Small |1-2| StudentShort'
>>> line = "Men = Small |1-2| Men"
>>> if re.search(r"\bSmall\b",line):
print re.sub("^(\w+)|(\w+)$",lambda x:x.group()+"Short",line)
'MenShort = Small |1-2| MenShort'
上述代码的改进版本(由@thg435 建议):
def solve(strs, match, word):
if re.search(r"\b{0}\b".format(match), strs):
return re.sub(r"(^\w+|\w+$)","\g<0>{0}".format(word), strs)
>>> solve("Men = Small |1-2| Men", "Small", "Short")
'MenShort = Small |1-2| MenShort'
>>> solve("Student = Small |1-2| Student", "Small", "Short")
'StudentShort = Small |1-2| StudentShort'