Since I was curious to do this without regular expression, here is the version without:
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 cahracter 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
Output:
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: I would prefer a solution from Daniel Roseman.
source share