Python Challenge#2 =从字符串中删除字符

Alp*_*ted 2 python-3.x

我有代码:

theory = """}#)$[]_+(^_@^][]_)*^*+_!{&$##]((](}}{[!$#_{&{){
*_{^}$#!+]{[^&++*#!]*)]%$!{#^&%(%^*}@^+__])_$@_^#[{{})}$*]#%]{}{][@^!@)_[}{())%)
())&#@*[#}+#^}#%!![#&*}^{^(({+#*[!{!}){(!*@!+@[_(*^+*]$]+@+*_##)&)^(@$^]e@][#&)(
%%{})+^$))[{))}&$(^+{&(#%*@&*(^&{}+!}_!^($}!(}_@@++$)(%}{!{_]%}$!){%^%%@^%&#([+[
_+%){{}(#_}&{&++!@_)(_+}%_#+]&^)+]_[@]+$!+{@}$^!&)#%#^&+$@[+&+{^{*[@]#!{_*[)(#[[
]*!*}}*_(+&%{&#$&+*_]#+#]!&*@}$%)!})@&)*}#(@}!^(]^@}]#&%)![^!$*)&_]^%{{}(!)_&{_{
+[_*+}]$_[#@_^]*^*#@{&%})*{&**}}}!_!+{&^)__)@_#$#%{+)^!{}^@[$+^}&(%%)&!+^_^#}^({
*%]&@{]++}@$$)}#]{)!+@[^)!#[%@^!!"""

#theory = open("temp.txt")

key = "#@!$%+{}[]_-&*()*^@/"
new2 =""

print()
for letter in theory:
    if letter not in key:
        new2 += letter

print(new2)
Run Code Online (Sandbox Code Playgroud)

这是解决python挑战的测试代码#2:http://www.pythonchallenge.com/pc/def/ocr.html

唯一的麻烦是,我写的代码似乎留下了很多空白,但我不确定为什么.

关于如何去除不必要的白色的任何想法?换句话说,我希望代码返回"e"而不是"e".

jfs*_*jfs 7

挑战在于找到一个罕见的角色.你可以用collections.Counter它:

from collections import Counter

c = Counter(theory)
print(c.most_common()[-1])
Run Code Online (Sandbox Code Playgroud)

产量

('e', 1)
Run Code Online (Sandbox Code Playgroud)

可以使用.strip()以下方法删除不必要的空格:

new2.strip()
Run Code Online (Sandbox Code Playgroud)

也加入'\n'key作品.