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' .
0
正则表达式可能?
import re
my_string = "Mary had a little lamb"
len(re.findall("a", my_string))
5
使用计数:
string = "count the number of counts in string to count from."
x = string.count("count")
x = 2 .
0
这将为您提供字符串中每个字符的出现 . O / P也是字符串格式:
def count_char(string1):
string2=""
lst=[]
lst1=[]
for i in string1:
count=0
if i not in lst:
for j in string1:
if i==j:
count+=1
lst1.append(i)
lst1.append(count)
lst.append(i)
string2=''.join(str(x) for x in lst1)
return string2
print count_char("aabbacddaabbdsrchhdsdg")
9
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))
my_string = "Mary had a little lamb"
# simplest solution, using count, is case-sensitive
my_string.count("m") # yields 1
import re
# case-sensitive with regex
len(re.findall("m", my_string))
# three ways to get case insensitivity - all yield 2
len(re.findall("(?i)m", my_string))
len(re.findall("m|M", my_string))
len(re.findall(re.compile("m",re.IGNORECASE), my_string))
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()
2
a = 'have a nice day'
symbol = 'abcdefghijklmnopqrstuvwxyz'
for key in symbol:
print key, a.count(key)
17 回答
正如其他答案所说,使用字符串方法count()可能是最简单的,但如果你经常这样做,请查看collections.Counter:
更多信息here
count 绝对是计算字符串中字符出现次数最简洁有效的方法,但我尝试使用 lambda 提出一个解决方案,如下所示:
这将导致:
此外,还有一个优点是,如果句子是包含与上述相同字符的子字符串列表,那么由于使用了
in
,这也给出了正确的结果 . 看一看 :这也导致:
但当然,只有在这种特殊情况下检查单个字符的出现时才会起作用,例如
'a'
.正则表达式可能?
使用计数:
x = 2 .
这将为您提供字符串中每个字符的出现 . O / P也是字符串格式:
只不过这个恕我直言 - 你可以添加上层或下层方法
str.count(a)
是计算字符串中单个字符的最佳解决方案 . 但是如果你需要计算更多的字符,你必须读取整个字符串的次数,而不是你想要计算的字符数 .这项工作的更好方法是:
因此,您将拥有一个dict,它返回字符串中每个字母的出现次数,如果不存在则返回
0
.对于不区分大小写的计数器,您可以通过子类化
defaultdict
来覆盖mutator和accessor方法(基类'是只读的):这个简单直接的功能可能会有所帮助:
你可以使用count():
如果你想要不区分大小写(当然还有正则表达式的所有功能),正则表达式非常有用 .
请注意,正则表达式版本的运行时间大约为十倍,这可能仅在my_string非常长或代码在深层循环内时才会出现问题 .
“不使用count来找到你想要字符串的字符”方法 .