完成一项练习,查找字符串中最常见的字母(不包括标点符号),结果应为小写。因此,在示例中 "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
中大小写并未更改为较低 - 标点符号不会从
文本
字符串中永久删除
最佳答案
有几个问题:
字符串是不可变的。这意味着
lower()
和replace()
等函数返回结果并保留原始字符串不变。您需要将该返回值分配到某处。lower()
可以对整个字符串进行操作:text = text.lower()
。
有关如何从字符串中删除标点符号的一些想法,请参阅 Best way to strip punctuation from a string in Python
关于python - 字符串中最常见的字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27694014/