Your other question suggests that you might be translating a very long string (a PDF file). In that case, using the string translate
method will be quicker than doing a character-by-character for-loop over the string:
test.py:
import string
infile='filename.pdf'
outfile='newfile.pdf'
with open(infile,'r') as f:
text=f.read()
def using_translate():
start_chars=''.join(chr(n) for n in range(256) if not chr(n).isspace())
end_chars=''.join(chr((ord(c)+2)%256) for c in start_chars)
table = string.maketrans(start_chars,end_chars)
return text.translate(table)
def using_for_c_in_text():
return ''.join(chr((ord(c) + 2)%256) if not c.isspace() else c for c in text)
This shows the results of a timeit run using a 1M pdf file:
# % python -mtimeit -s"import test" "test.using_for_c_in_text()"
# 10 loops, best of 3: 821 msec per loop
# % python -mtimeit -s"import test" "test.using_translate()"
# 100 loops, best of 3: 4.36 msec per loop
PS: Many answers (including mine at one point) used chr(ord(c) + 2)
. This throws a TypeError if ord(c)+2>=256
. To avoid the TypeError, you could use chr((ord(c) + 2)%256)
.