Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
string.maketrans() method not working
-
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.
-
This is my code:
import string
str = 'map.html'
i = 'abcdefghijklmnopqrstuvwxyz'
o = 'cdefghijklmnopqrstuvwxyzab'
table = string.maketrans(i, o)
print (str.translate(table)) -
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 thestr
type properly anymore) but normally it would only affect your own code. Here in Pythonista it also breaks some internalprint
code. The solution is to choose a different name for your string - call its
orname
orurl
or whatever you like. -
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)
-
I see. Now, it worked perfectly.
So, in pythonista, this word already taken.Many thanks!
-
In Python this word is taken.
-
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 aTypeError
, 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 originalstr
class anymore. The same goes for other standard types likeint
,float
,list
,dict
, etc.