문제

In Python 2.x, using backticks to get decimal string from int object is Horrible? Because backticks are repr(), not str()? I have noticed that when I answering this question.

In Python source, they have same function in Python source, intobject.c

(reprfunc)int_to_decimal_string,            /* tp_repr */
....
(reprfunc)int_to_decimal_string,            /* tp_str */

What do you think?

도움이 되었습니까?

해결책

Well, I wouldn't say it's "horrible", but I feel it isn't right for at least four reasons:

  1. str(my_number) states your intent more clearly than surrounding my_number by backticks. (See "Readability counts" in the Zen of Python).

  2. The implementation of Python in C is just one possible implementation; there is Jython, IronPython, PyPy and so on, and unless there is an explicit statement in the Python specification somewhere that repr() and str() is the same for integer objects, I wouldn't to rely on that behaviour.

  3. Backticks are gone in Python 3.x.

  4. If your number happens to be so large that it cannot be represented by an int, Python promotes it automatically to a long integer, and for that, repr() and str() differs.

See this example:

>>> x = 1234567890
>>> y = x ** 3
>>> `y`
'1881676371789154860897069000L'
>>> str(y)
'1881676371789154860897069000'

다른 팁

Yes. Using backticks for anything is horrible.

You've got str(i), you've got '%d' % i, you've got .format(i); if you want the repr then say so directly with repr() or %r or whatever.

There was never a good reason to use backticks, they just made code less readable and much harder to parse. They are gone in Python 3.

2.X: Using backticks for anything is horrible. Use repr() or str() as required.

3.X: Backticks have vanished! Three cheers!!

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top