简体   繁体   English

如何替换 Python 字符串中的所有字符?

[英]How do I replace all characters in a Python string?

I found a solution on stackoverflow but it doesn't seem to work.我在 stackoverflow 上找到了一个解决方案,但它似乎不起作用。 I have made a string scanner that checks for character frequency and then replaces all characters with the "real" characters.我制作了一个字符串扫描仪,用于检查字符频率,然后用“真实”字符替换所有字符。 I've made sure that the character recognition works but when I try replacing all characters in a string they no longer match up with the expected/calculated characters (when I try replacing for example only 2 characters it works fine and matches up perfectly).我已经确保字符识别有效,但是当我尝试替换字符串中的所有字符时,它们不再与预期/计算出的字符匹配(例如,当我尝试仅替换 2 个字符时,它可以正常工作并完美匹配)。 Here is my replacement code:这是我的替换代码:

print(text.replace(re,'e').replace(rt,'t').replace(ra,'a').replace(ro,'o').replace(ri,'i').replace(rn,'n').replace(rs,'s').replace(rr,'r').replace(rh,'h').replace(rl,'l').replace(ru,'u').replace(rc,'c').replace(rm,'m').replace(rf,'f').replace(ry,'y').replace(rw,'w').replace(rg,'g').replace(rp,'p').replace(rb,'b').replace(rv,'v').replace(rk,'k').replace(rx,'x').replace(rq,'q').replace(rj,'j').replace(rz,'z').replace(rd,'d'))

You might want to take a look at translate .您可能想看看translate Your code would probably look something like您的代码可能看起来像

text = text.translate(str.maketrans('abcd...', ''.join([ra, rb, rc, rd...]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Python中替换字符串中的字符? - How do I replace characters in a string in Python? 在 Pandas Python 中,如何替换字符串列中的字符? - In Pandas Python how do i replace Characters in String column? 如何将字符串拆分为字符并用浮点值替换字符以找到 Python 中原始字符串的总和? - How do I split string into characters and replace characters with float values to find the sum of original string in Python? 如何将字符与Python中某个字符串中的所有字符进行比较? - How do I compare a character to all the characters in some string in Python? 如何正确替换字符串中的字符? - How do I correctly replace characters in a string? 如何在Python中用“”替换字符串中的所有标点符号? - How do I replace all punctuation in my string with “” in Python? 如何使用.replace()函数将字符串的最后4个字符(最后4个字符除外)更改为#符号? - How do I use the .replace() function to change all but the last 4 characters of a string into the # symbol? 在Python中,如何替换字符串中的所有非UTF-8字符? - In Python, how to replace all non-UTF-8 characters in a string? 如何在Python中替换字符串中的字符,但不使用字符串方法? - How can I replace characters in a string in Python, but not using string methods? 如何在Python 3.5中为使用随机替换字符串中字符的函数编写doctest? - How do I write a doctest in python 3.5 for a function using random to replace characters in a string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM