学习笔记,备忘录。。。
使用translate()函数删除指定字符,报错内容为函数内只需要一个参数,但提供了两个。原因是python2.7版本之后translate()内的参数从两个变成了一个。
目录:
import string
old_sentence='I love you,but you do not love me.I feel sad!?!?'
remove=string.punctuation
table=str.maketrans('','',remove)
new_sentence=old_sentence.translate(table)
print(old_sentence)
print(new_sentence)
I love you,but you do not love me.I feel sad!?!?
I love youbut you do not love meI feel sad!?
后两个标点符号为中文标点符号,无法去除。
通过使用str.maketrans
函数来创建一个表。它可以使用各种参数,但是需要三种Arg形式。我们忽略前两个ARG,因为它们用于将字符映射成其他字符。第三个Arg是我们希望删除的字符。
old_sentence='I love you,but you do not love me.I feel sad!23333'
remove='aeiou123'
table=str.maketrans('_','_',remove)
new_sentence=old_sentence.translate(table)
print(old_sentence)
print(new_sentence)
I love you,but you do not love me.I feel sad!23333
I lv y,bt y d nt lv m.I fl sd!
old_sentence='I love you,but you do not love me.I feel sad!23333'
remove='aeiou'
replace='12345'
table=str.maketrans(remove,replace)
new_sentence=old_sentence.translate(table)
print(old_sentence)
print(new_sentence)
I love you,but you do not love me.I feel sad!23333
I l4v2 y45,b5t y45 d4 n4t l4v2 m2.I f22l s1d!23333
报错内容:ValueError: the first two maketrans arguments must have equal length
maketrans函数中的两个参数长度必须相同,非等长的无法进行替换。
参考:
1.https://stackoverflow.com/questions/39375712/translate-takes-exactly-one-argument-2-given-in-python-error
2.http://www.runoob.com/python3/python3-string-translate.html