Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中maketrans和replace的区别是什么?_Python_String_Punctuation - Fatal编程技术网

Python中maketrans和replace的区别是什么?

Python中maketrans和replace的区别是什么?,python,string,punctuation,Python,String,Punctuation,如果以前有人问过,我会道歉。我正在试着去掉绳子上的刺。我知道怎么做,但我不理解Python中maketrans和replace之间的区别。更具体地说,为什么下面的代码场景1删除了传入字符串中的所有标点符号,而场景2没有 情景1 def average(x): table = x.maketrans('.,?!:','$$$$$') x = x.translate(table) x = x.replace('$', '') lst1 = x.split()

如果以前有人问过,我会道歉。我正在试着去掉绳子上的刺。我知道怎么做,但我不理解Python中maketrans和replace之间的区别。更具体地说,为什么下面的代码场景1删除了传入字符串中的所有标点符号,而场景2没有

情景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))
.replace()
执行子字符串替换-它尝试将第一个参数的全部匹配为一个块,并将其替换为第二个参数的全部


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

谢谢!我现在明白了。