maketrans和Python中的替换有什么区别?

时间:2015-02-02 05:19:24

标签: python string punctuation

如果之前有人问过,请道歉。我试图从字符串中删除标点符号。我知道怎么做,但我不明白maketrans和Python之间的区别。更具体地说,为什么下面的代码方案1从传入的字符串中删除所有标点符号,但是方案2没有?

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))

情景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))

1 个答案:

答案 0 :(得分:2)

.replace()执行 substring 替换 - 它尝试将第一个参数的整体匹配为一个块,并将其替换为第二个参数的全部。

.maketrans + .translate执行字符级翻译 - 它会将第一个参数中的每个字符替换为第二个字符中的相应字符。