完成一个练习,找出字符串中最常见的字母,不包括标点符号,结果应该是小写。所以在示例"HHHHello World!!!!!!!!!!"
中,结果应该是"h"
。在
我目前所拥有的:
text=input('Insert String: ')
def mwl(text):
import string
import collections
for p in text:
p.lower()
for l in string.punctuation:
for x in text:
if x==l:
text.replace(x,'')
collist=collections.Counter(text).most_common(1)
print(collist[0][0])
mwl(text)
如果您能帮助我理解原因:
text
中,大小写未更改为较低text
字符串中永久删除标点符号
你可以试试这个:
或使用str.翻译删除标点:
^{pr2}$使用您自己的代码,您需要将文本重新分配给更新的字符串:
此外,您可以在以下代码中使用,而不是在代码中循环文本:
有几个问题:
字符串是不可变的。这意味着像
lower()
和replace()
这样的函数返回结果并保持原始字符串不变。您需要将返回值赋给某个地方。lower()
可以对整个字符串进行操作:text = text.lower()
。有关如何从字符串中删除标点字符的一些想法,请参见Best way to strip punctuation from a string in Python
相关问题 更多 >
编程相关推荐