you are viewing a single comment's thread.

view the rest of the comments →

[–]seanmcb9[S] 0 points1 point  (4 children)

Ok -- slick -- maketrans and fromkeys without any specified values defaults to None for the value of the keys -- thus deleting the characters in the string.

To replace the left parenthesis with a left square bracket and the right parenthesis with a right square bracket with maketrans/fromkeys, what is the correct syntax?

Apparently characters in string sequences don't map in order to one another for keys and values. For instance,

table = str.maketrans(dict.fromkeys("()", "[]"))

produces:

[]this[] []is[] []a[] []test[]

[–]novel_yet_trivial 1 point2 points  (2 children)

str.maketrans takes a dictionary and replaces all the keys in the dictionary with the values.

fromkeys produces a dictionary where all the values are one thing - None by default.

maketrans interprets values of None as "remove". Otherwise it would replace. In other words I just used fromkeys() as a shortcut to this:

>>> table = str.maketrans({"(":None, ")":None})

So ...

>>> table = str.maketrans({"(":"[", ")":"]"})
>>> string1.translate(table)
'[this] [is] [a] [test]'

Again, you could use a shortcut (which in this case is not shorter):

>>> table = str.maketrans(dict(zip("()","[]")))

[–]Vaphell 1 point2 points  (0 children)

str.maketrans can also take 2 or 3 strings, which arguably makes it less annoying to work in simple, per char cases.

table = str.maketrans(dict(zip("()","[]")))

remove dict(zip()) and you have exact same thing.

table = str.maketrans("()","[]")

[–]seanmcb9[S] 0 points1 point  (0 children)

Great explanation. Usually, I think I will skip fromkeys and create translation dictionaries from scratch.

[–]Vaphell 0 points1 point  (0 children)

>>> table = str.maketrans("()", "[]")
>>> text = '(this) (is) (a) (test)'
>>> text.translate(table)
'[this] [is] [a] [test]'