Have a string,
'ANNA BOUGHT AN APPLE AND A BANANA'
and want to replace 'AN' and get
'ANNA BOUGHT X APPLE AND A BANANA'
but simple code:
text.replace('AN', 'X')
returns:
XNA BOUGHT X APPLE XD A BXXA
How to make it work?
Have a string,
'ANNA BOUGHT AN APPLE AND A BANANA'
and want to replace 'AN' and get
'ANNA BOUGHT X APPLE AND A BANANA'
but simple code:
text.replace('AN', 'X')
returns:
XNA BOUGHT X APPLE XD A BXXA
How to make it work?
This code works for every case (begging/middle/end of the string, with or without punctuation marks):
import re
your_string = 'AN ANNA BOUGHT AN APPLE AND A BANANA AN'
replaced_strig = re.sub(r'\bAN\b', 'X', your_string)
If you want to search for the word AN, you should use text.replace(' AN ', ' X ')
with the spaces. That way you'll be replacing only the word and avoiding other occurrences
Let string = ANNA BOUGHT AN APPLE AND A BANANA
Then myList = string.split(' ')
It will return myList = ['ANNA', 'BOUGHT', 'AN', 'APPLE', 'AND', 'A', 'BANANA']
Then you can do the following
myList[myList.index('AN')] = 'X'
In case multiple 'AN' is present, we can do the following
for i in range(len(myList)):
if myList[i] == 'AN':
myList[i] = 'X'
You can use regular expressions - note the use of \b
for word boundaries:
import re
line = 'ANNA BOUGHT AN APPLE AND A BANANA'
print(re.sub(r'\bAN\b', 'X', line))
or a solution without regular expressions (does not preserve the exact amount of whitespace between words, and may not be exactly equivalent if there is punctuation also):
line = 'ANNA BOUGHT AN APPLE AND A BANANA'
print(' '.join('X' if word == 'AN' else word
for word in line.split()))
regex is the best way to have such manipulation and even more complex ones, it is a bit intimidating to learn, but once you are done with it it gets really easy
import re
text = 'ANNA BOUGHT AN APPLE AND A BANANA'
pattern = r'(AN)'
new = re.sub(pattern,'X',text)
print(new)
regex is the way - with lookahead and lookbehind
import re
line = 'AN ANNA BOUGHT AN APPLE AND A BANANA AN. AN'
pattern='((?<=^)|(?<=\W))AN(?=\W|$)'
p = re.compile(pattern)
print(p.sub('X', line))
input: AN ANNA BOUGHT AN APPLE AND A BANANA AN. AN
result: X ANNA BOUGHT X APPLE AND A BANANA X. X