Skip to content Skip to sidebar Skip to footer

Replace Word, But Another Word With Same Letter Format Got Replaced

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 : 'ba

Solution 1:

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

defslangwords(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 inenumerate(words):
        words[i] = replacements.get(word, word)
    return" ".join(words)

Solution 2:

You just need to reverse the order of replace:

def slangwords(kalimat):
    words = kalimat.split(' ')
    for word in words:
        if any(x in word for x in "bgt"):
            kalimat = kalimat.replace("bgt","banget")

        if any(x in word for x in "bg"):
            kalimat = kalimat.replace("bg","bang")
    return kalimat
print(slangwords('bg bgt'))

If you would like to replace many words, you can put them in dictionary (note that the order matters here as well):

replace_words = { 'bgt' :'banget', 'bg': 'bang'}

defslangwords(kalimat):
    words = kalimat.split(' ')
    for word in words:
      for wrd, repl in replace_words.items():
        kalimat = kalimat.replace(wrd, repl)
    return kalimat

Solution 3:

Here is another approach. You just need a dictionary of the substitutions. Using get enable to set the default value if the jey is missing (here the same word).

def slangwords(kalimat, sub={'bg': 'bang', 'bgt': 'banget'}):
    return' '.join([sub.get(w, w) for w in kalimat.split(' ')])
>>> slangwords('bg bgt abc')
'bang banget abc'

Post a Comment for "Replace Word, But Another Word With Same Letter Format Got Replaced"