pK. pK. - 9 months ago 99
Python Question

TypeError: translate() takes exactly one argument (2 given)

My code is running fine on python 2.x versions but when I'm trying to run it on python 3.x version, it's giving error.

subject: need to abbreviate any message in sms encoding.

Code:

def sms_encoding(data):
#start writing your code here
print(data)
data.split(" ")
data_list=data.split(" ")
sms_encd=[]
final_sms=""
for i in range(len(data_list)):
if data_list[i].lower() in ['a','e','i','o','u']:
sms_encd.append(data_list[i])
elif len(data_list[i])>1:
a = data_list[i].translate(None,'aeiouAEIOU')
sms_encd.append(a)
for j in range(len(sms_encd)):
final_sms += str(sms_encd[j])+" "
return final_sms[:-1]
data="I will not repeat mistakes"
print(sms_encoding(data))


Output:

2.x versions:

I will not repeat mistakes
I wll nt rpt mstks


3.x versions:

I will not repeat mistakes
Traceback (most recent call last):
File "python", line 18, in <module>
File "python", line 12, in sms_encoding
TypeError: translate() takes exactly one argument (2 given)


why
translate()
is not working? is there any alternative workaround?

Answer Source

You need to compare Python 3's str.translate() with Python 2's unicode.translate(). Both take a mapping from codepoint (an integer) to a replacement (either another integer or a single-character Unicode e string).

The str type has a static method str.maketrans() that takes the characters-to-delete (the second argument to Python 2's str.translate()) as the third argument, to produce such a map. Use that here:

map = str.maketrans('', '', 'aeiouAEIOU')
a = data_list[i].translate(map)

This outputs a dictionary mapping each of the vowel codepoints to None:

>>> str.maketrans('', '', 'aeiouAEIOU')
{97: None, 101: None, 105: None, 111: None, 117: None, 65: None, 69: None, 73: None, 79: None, 85: None}