我试图弄清楚如何计算一个字符串中出现3次的字母数。字符串来自raw_input()
。
例如,如果我的输入是:
abceeedtyooo
输出应为:2
这是我当前的代码:
print 'Enter String:'
x = str(raw_input (""))
print x.count(x[0]*3)
要计算字符串中的字符数,可以使用collections.Counter
:
>>> from collections import Counter
>>> counter = Counter("abceeedtyooo")
>>> print(counter)
Counter({'e': 3, 'o': 3, 'a': 1, 'd': 1, 'y': 1, 'c': 1, 'b': 1, 't': 1})
然后,您可以按以下方式过滤结果:
>>> result = [char for char in counter if counter[char] == 3]
>>> print(result)
['e', 'o']
如果只想匹配连续的字符,则可以使用正则表达式(参见re
):
>>> import re
>>> result = re.findall(r"(.)\1\1", "abceeedtyooo")
>>> print(result)
['e', 'o']
>>> result = re.findall(r"(.)\1\1", "abcaaa")
>>> print(result)
['a']
如果同一字符多次连续出现3次(例如,在上"aaabcaaa"
,它将匹配'a'
两次),这也将匹配。匹配项不重叠,因此在"aaaa"
匹配项上只会匹配一次,但在"aaaaaa"
匹配项上会匹配两次。如果您不希望连续的字符串有多个匹配项,请将regex修改为r"(.)\1\1(?!\1)"
。为了避免匹配任何出现的字符更连续超过3次,使用(.)(?<!(?=\1)..)\1{2}(?!\1)
。这可以解决Python无法处理的regex模块的问题(?<!\1)
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句