如何替换多行字符串中的每个字符,保留空格和\r \n?
这是一个多行字符串的例子,比如:
abc 123
456 def
想要的结果(序号加2):
cde 345
678 fgh
如果我使用:
text = "abc 123\n456 def"
add2=''.join(chr(ord(c)+2) for c in text)
print text
print add2
那么空格和\r \n也会被替换掉,我该怎么做才能在第二行代码中不替换空格
、\r
或\n
呢?
补充说明:这是对这个问题的后续讨论。
4 个回答
2
你可以简单地检查这个字符是否是字母或数字,如果不是,就保留原来的字符:
add2 = ''.join(chr(ord(c)+2) if c.isalnum() else c for c in text)
请注意,对某些字符(比如'y'、'z'、'9'、'0'等)这样做可能不会得到你想要的结果。也就是说,'y'不会变成'a',而是变成'{'。
3
你提到的另一个问题表明,你可能在处理一个非常长的字符串(比如一个PDF文件)。在这种情况下,使用字符串的 translate
方法会比逐个字符地用循环处理要快得多:
这是一个示例文件: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)
这里展示了使用一个1M大小的PDF文件进行时间测试的结果:
# % 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
顺便说一下,很多回答(包括我之前的一个)使用了 chr(ord(c) + 2)
。如果 ord(c)+2>=256
,这会导致一个类型错误(TypeError)。为了避免这个错误,你可以使用 chr((ord(c) + 2)%256)
。
1
add2 = ''.join(chr(ord(c) + 2) if c not in "\n\r " else c for c in text)
当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。