Im trying to replace a word in python, but another word with same letter format got replaced
example :
initial : 'bg bgt'
goal : 'bang banget'
current result : 'bang bangt'
heres what my code currently looks like:
def slangwords(kalimat):words = kalimat.split(' ')for word in words:if any(x in word for x in "bg"):kalimat = kalimat.replace("bg","bang")if any(x in word for x in "bgt"):kalimat = kalimat.replace("bgt","banget")return kalimatprint(slangwords('bg bgt'))
n ill appreciate more if u can show me how to replace these slangword more effective and efficient, thanks
That is because you replace bg
before bgt
(which is a bigger substring), you need to change the order.
Also, you don't need if any(x in word for x in "bg")
, that checks if every letter is present in the word and not if the substring is present in the same order, plus, you don't need any verification before using str.replace
, if the strin isn't there, it won't do anything
You just need
def slangwords(kalimat):return kalimat.replace("bgt", "banget").replace("bg", "bang")
Better and not order-dependent
Use a dictionnary, and replace each word with its substitute
def slangwords(kalimat):replacements = {'bg': 'bang','bgt': 'banget'}words = kalimat.split(' ')for i, word in enumerate(words):words[i] = replacements.get(word, word)return " ".join(words)