New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
PEP 378 uses replace where translate may work better #54387
Comments
PEP-378 states; format(n, "6,f").replace(",", "X").replace(".", ",").replace("X", ".") This is complex and relatively slow. A better technique, which IMHO the proposal should high-lighted, would be: swap_commas_and_periods = bytes.maketrans(b',.', b'.,')
format(n, "6,f").translate(swap_commas_and_periods) While performing the maketrans each time a string is formatted is slower than the triple replace, calling it once and caching the result is faster. I have tested with with the 3.1 interpreter; example timings follow. >>> Timer("""
'1,234,567.89'.replace(',', 'X').replace('.', ',').replace('X', '.')
""").timeit()
3.0645400462908015
>>> Timer("""
'1,234,567.89'.translate(swap_commas_and_periods)
""", """
swap_commas_and_periods = bytes.maketrans(b',.', b'.,')
""").timeit()
2.276630409730846
>>> Timer("""
'1,234,567.89'.translate(bytes.maketrans(b',.', b'.,'))
""").timeit()
3.760715677551161 |
The text in question is talking about 'replace' as a general mechanism for 'fixing' the separator character, and as such I don't think introducing translate would enhance the exposition. I suppose it could be added in a footnote. |
The text in question is also talking about the problems with using 'replace' to swap pairs of characters, so a better, alternate, process would be valuable, especially for anyone unaware of the translate method. |
Sorry, the text needs to stand as-is. The technique of t=x; x=y; y=t is somewhat basic BTW, the PEP itself is not primary documentation Feel free to post your recipe on ASPN or on |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: