New submission from samwyse <samw...@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: d...@python components: Documentation messages: 119427 nosy: d...@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 <rep...@bugs.python.org> <http://bugs.python.org/issue10178> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com