This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author samwyse
Recipients docs@python, samwyse
Date 2010-10-23.14:05:22
SpamBayes Score 0.00041926114
Marked as misclassified No
Message-id <1287842725.3.0.632950856337.issue10178@psf.upfronthosting.co.za>
In-reply-to
Content
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
History
Date User Action Args
2010-10-23 14:05:25samwysesetrecipients: + samwyse, docs@python
2010-10-23 14:05:25samwysesetmessageid: <1287842725.3.0.632950856337.issue10178@psf.upfronthosting.co.za>
2010-10-23 14:05:24samwyselinkissue10178 messages
2010-10-23 14:05:22samwysecreate