を使用したこのようなもの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'