Ваш другой вопрос предполагает, что вы можете переводить очень длинную строку (файл PDF). В этом случае использование метода string translate
будет быстрее, чем посимвольный цикл for для строки:
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)
Здесь показаны результаты выполнения таймита с использованием файла PDF размером 1 МБ:
# % 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: во многих ответах (включая мой в одной точке) chr(ord(c) + 2)
. Это выдает ошибку TypeError, если ord(c)+2>=256
. Чтобы избежать ошибки TypeError, вы можете использовать chr((ord(c) + 2)%256)
.