Search code examples
pythonstringpunctuation

What is difference between maketrans and replace in Python?


Apologies if this has been asked before. I am trying to remove punctation from a string. I know how to do it, but I do not understand the difference between maketrans and replace in Python. More specifically, why does code scenario 1 below remove all the punctuation from incoming strings, but scenario 2 does not?

SCENARIO 1

def average(x):
    table = x.maketrans('.,?!:','$$$$$')
    x = x.translate(table)
    x = x.replace('$', '')
    lst1 = x.split()
    lst2 = []
    for i in lst1:
        length = len(i)
        lst2.append(len(i)) 
    average = sum(lst2) / len(lst2)

    return average

str1 = input("Enter a sentence:")

print('The average amount of chars in that sentence is: ', average(str1))

SCENARIO 2

def average(x):
    x = x.replace('.,?!:','')
    lst1 = x.split()
    lst2 = []
    for i in lst1:
        length = len(i)
        lst2.append(len(i)) 
    average = sum(lst2) / len(lst2)

    return average

str1 = input("Enter a sentence:")

print('The average amount of chars in that sentence is: ', average(str1))

Solution

  • .replace() does a substring replace - it tries to match the entirety of the first argument as one chunk, and replace it with the entirety of the second argument.

    .maketrans + .translate does a character-level translation - it replaces each individual character from the first argument with the corresponding character in the second.