<p>因为我一直很想在没有regex的情况下这样做,下面是一个没有:</p>
<pre><code>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
</code></pre>
<p>输出为:</p>
^{pr2}$
<p>附言:我更喜欢丹尼尔·罗斯曼的解决方案。在</p>