[New-bugs-announce] [issue10178] PEP 378 uses replace where translate may work better
samwyse
report at bugs.python.org
Sat Oct 23 16:05:25 CEST 2010
New submission from samwyse <samwyse at gmail.com>:
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
----------
assignee: docs at python
components: Documentation
messages: 119427
nosy: docs at python, samwyse
priority: normal
severity: normal
status: open
title: PEP 378 uses replace where translate may work better
type: behavior
versions: Python 2.7, Python 3.1
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue10178>
_______________________________________
More information about the New-bugs-announce
mailing list