Forum Archive

string.maketrans() method not working

craftmojo

Today, I tried to code in pythonista for ios, everything seems okay. But, when I use maketrans method , it not working at all. What happened? I tried the code in pycharm, it worked perfectly.

Please help.

craftmojo

This is my code:

import string
str = 'map.html'
i = 'abcdefghijklmnopqrstuvwxyz'
o = 'cdefghijklmnopqrstuvwxyzab'
table = string.maketrans(i, o)
print (str.translate(table))

dgelessus

str is the name of Python's string type. In your code, you're overwriting it with another object. This is not a good idea (it means that you cannot use the str type properly anymore) but normally it would only affect your own code. Here in Pythonista it also breaks some internal print code. The solution is to choose a different name for your string - call it s or name or url or whatever you like.

Phuket2

I had just done this

import string

#str = 'map.html'
s = 'map.html'
i = 'abcdefghijklmnopqrstuvwxyz'
o = 'cdefghijklmnopqrstuvwxyzab'

table = string.maketrans(i, o)
print str.translate(s, table)
craftmojo

I see. Now, it worked perfectly.
So, in pythonista, this word already taken.

Many thanks!

ccc

In Python this word is taken.

dgelessus

Exactly. str is the string class, and you can use it to convert an object to a string. For example, str(42) is the same as '42'. This is important when you want to do something like this:

print("Your score is: " + str(42))

Without using str, you would get a TypeError, because you can't add a string and a number.

This means that if you assign something different to the name str, you cannot use the original str class anymore. The same goes for other standard types like int, float, list, dict, etc.