由于我一直对没有正则表达式的情况感到好奇,所以这里有一个没有的版本:
MYSTR = ["H3", "H3b", "aH3", "H3 mmmoleculeH3 H3",
"H3 mmmoleculeH3 H3b", "H3 mmmoleculeH3 H3b H3"]
FIND = "H3"
LEN_FIND = len( FIND )
REPLACE = "H1"
for entry in MYSTR:
index = 0
foundat = []
# Get all positions where FIND is found
while index < len( entry ):
index = entry.find( FIND, index )
if index == -1:
break
foundat.append( index )
index += LEN_FIND
print "IN: ", entry,
for loc in foundat:
# Check if String is starting with FIND
if loc == 0:
# Check if String only contains FIND
if LEN_FIND == len( entry ):
entry = REPLACE
# Check if the character after FIND is blank
elif entry[LEN_FIND] == " ":
entry = entry[:loc] + REPLACE + entry[loc + LEN_FIND:]
else:
# Check if character before FIND is blank
if entry[loc - 1] == " ":
# Check if FIND is the last part of the string
if loc + LEN_FIND + 1 > len( entry ):
entry = entry[:loc] + REPLACE + entry[loc + LEN_FIND:]
# Check if character after FIND is blank
elif entry[loc + LEN_FIND] == " ":
entry = entry[:loc] + REPLACE + entry[loc + LEN_FIND:]
print " OUT: ", entry
输出是:
IN: H3 OUT: H1
IN: H3b OUT: H3b
IN: aH3 OUT: aH3
IN: H3 mmmoleculeH3 H3 OUT: H1 mmmoleculeH3 H1
IN: H3 mmmoleculeH3 H3b OUT: H1 mmmoleculeH3 H3b
IN: H3 mmmoleculeH3 H3b H3 OUT: H1 mmmoleculeH3 H3b H1
PS:我更喜欢 Daniel Roseman 的解决方案。