4 Answers
4

You shouldn't use chr or str as names because they shadow the builtin chr and str methods. If you then wanted to use str() you'd be out of luck because str is now a string instead of a function. Given that your function deals with both strings and character ordinals it is not unlikely that these could be used. string is a potential improvement, it can occasionally cause trouble if you're trying to use the string module of the same name.

You should also add comments and a docstring. Docstrings are basically comments that are programmatically accessible so that other users can understand how to use your function.

def chrtodec(str):
"""Converts a string to a float using character ordinal positions."""

I think you have another big problem though, which is invalid input handling. Take a look at these:

Clearly there are problems here when you have characters other than numbers, so I think what you should do is raise a ValueError when an invalid string is passed. You already have the tools to do this figured out of course if you just check that a character's ordinal fits in the right range.

Also you could add support for negative numbers by checking at the start if the first character is ord('-').

negative = ord(str[0]) == ord('-')

This evaluates the expression str[0] == ord('-') and sets negative as the boolean result. Note that to make this compatible with the error handling I suggested, you should then remove the first character from str. And probably update the error message and docstring too.

\$\begingroup\$@Barry thanks for commenting! This is indeed slower than OP's solution but I would avoid premature opimization in this case. I find it so much more readable. This is a single expression. Look how similar this is to the mathematical definition of a positional number system. Also this uses many built-in functions enumerate, reversed and sum thus delegating the work to Python itself as it is idiomatic\$\endgroup\$
– CaridorcSep 10 '15 at 10:23

\$\begingroup\$@Barry I refactored even more, the code has also become more testable and this is much faster to write than the original solution in my opinion\$\endgroup\$
– CaridorcSep 10 '15 at 11:30

\$\begingroup\$@Caridorc, I agree with Barry. I don't think the code is readable in first place.\$\endgroup\$
– CodeYogiSep 11 '15 at 4:12

I've come to love the "straight-to-the-point" Python syntax a lot, and I embrace the delicious syntactic sugar of the language; but I keep seeing really bad naming of things among Python programmers. Maybe try this?

\$\begingroup\$I agree, if you're trying to be short I'd at least use char.\$\endgroup\$
– SuperBiasedManSep 10 '15 at 8:34

2

\$\begingroup\$I don't think these names are better, either. The function does not convert a character to a decimal, but a string representing an integer in decimal notation to an integer.\$\endgroup\$
– mkrieger1Sep 10 '15 at 9:34