如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
当前回答
你可以使用循环和字典。
def count_letter(text):
result = {}
for letter in text:
if letter not in result:
result[letter] = 0
result[letter] += 1
return result
其他回答
python - 3. x:
"aabc".count("a")
Str.count (sub[, start[, end]]) 返回子字符串sub在范围[start, end]中不重叠出现的次数。可选参数start和end被解释为片表示法。
“不使用计数查找字符串中需要的字符”方法。
import re
def count(s, ch):
pass
def main():
s = raw_input ("Enter strings what you like, for example, 'welcome': ")
ch = raw_input ("Enter you want count characters, but best result to find one character: " )
print ( len (re.findall ( ch, s ) ) )
main()
count绝对是计算字符串中字符出现次数的最简洁和有效的方法,但我尝试使用lambda来提出一个解决方案,类似这样:
sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))
这将导致:
4
另外,这样做还有一个好处,如果句子是包含上述相同字符的子字符串列表,那么由于使用了in,这也会给出正确的结果。看看吧:
sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))
这也导致:
4
当然,这只会在检查单个字符的出现时起作用,例如在这种特殊情况下“a”。
Str.count (sub[, start[, end]]) 返回子字符串sub在范围[start, end]中不重叠出现的次数。可选参数start和end被解释为片表示法。
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
spam = 'have a nice day'
var = 'd'
def count(spam, var):
found = 0
for key in spam:
if key == var:
found += 1
return found
count(spam, var)
print 'count %s is: %s ' %(var, count(spam, var))