Replace lowercase ASCII characters with X in Python
Question: What is the cleanest, most Pythonic code for replacing lowercase characters
with 'X' in a string? For example, `ABCDEFGhijklmnopQRSTUVwxyz` would become
`ABCDEFGXXXXXXXXXQRSTUVXXXX`.


Answer: I'd use
[`str.translate()`](https://docs.python.org/2/library/stdtypes.html#str.translate)
for that; easily the fastest method. A regular expression cannot touch this
for speed.

Python 2 version:

    
    
    import string
    
    map = string.maketrans(string.ascii_lowercase, 'X' * len(string.ascii_lowercase))
    mapped = inputstring.translate(map)
    

Python 3 version:

    
    
    import string
    
    map = str.maketrans(dict.fromkeys(string.ascii_lowercase, 'X'))
    mapped = inputstring.translate(map)
    

Demo (Python 2):

    
    
    >>> import string
    >>> inputstring = 'ABCDEFGhijklmnopQRSTUVwxyz'
    >>> map = string.maketrans(string.ascii_lowercase, 'X' * len(string.ascii_lowercase))
    >>> inputstring.translate(map)
    'ABCDEFGXXXXXXXXXQRSTUVXXXX'
    

`str.translate()` is _orders of magniture_ faster here:

    
    
    >>> import timeit
    >>> import re
    >>> def regex_replace(s, _sub=re.compile(r'[a-z]').sub):
    ...     return _sub('X', s)
    ... 
    >>> regex_replace(inputstring)
    'ABCDEFGXXXXXXXXXQRSTUVXXXX'
    >>> timeit.timeit('f(s)', 'from __main__ import regex_replace as f, inputstring as s')
    2.6076979637145996
    >>> timeit.timeit('s.translate(m)', 'from __main__ import inputstring as s, map as m')
    0.13378620147705078
    

The `str.translate()` version manages to do the task _20 times_ faster.

