[docs] [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', '.')

>>> Timer("""
""", """
  swap_commas_and_periods = bytes.maketrans(b',.', b'.,')

>>> Timer("""
  '1,234,567.89'.translate(bytes.maketrans(b',.', b'.,'))

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>

More information about the docs mailing list