如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
如何计算字符串中字符出现的次数?
如。“a”在“Mary had a little lamb”中出现了4次。
当前回答
Python 3
有两种方法可以做到这一点:
1)内置函数count()
sentence = 'Mary had a little lamb'
print(sentence.count('a'))`
2)不使用函数
sentence = 'Mary had a little lamb'
count = 0
for i in sentence:
if i == "a":
count = count + 1
print(count)
其他回答
这是公认答案的延伸,你应该在文本中寻找所有字符的计数。
# Objective: we will only count for non-empty characters
text = "count a character occurrence"
unique_letters = set(text)
result = dict((x, text.count(x)) for x in unique_letters if x.strip())
print(result)
# {'a': 3, 'c': 6, 'e': 3, 'u': 2, 'n': 2, 't': 2, 'r': 3, 'h': 1, 'o': 2}
python - 3. x:
"aabc".count("a")
Str.count (sub[, start[, end]]) 返回子字符串sub在范围[start, end]中不重叠出现的次数。可选参数start和end被解释为片表示法。
a = "I walked today,"
c=['d','e','f']
count=0
for i in a:
if str(i) in c:
count+=1
print(count)
Python 3
有两种方法可以做到这一点:
1)内置函数count()
sentence = 'Mary had a little lamb'
print(sentence.count('a'))`
2)不使用函数
sentence = 'Mary had a little lamb'
count = 0
for i in sentence:
if i == "a":
count = count + 1
print(count)
Str.count (sub[, start[, end]]) 返回子字符串sub在范围[start, end]中不重叠出现的次数。可选参数start和end被解释为片表示法。
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4