如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
如何计算给定子字符串在Python字符串中出现的次数?
例如:
>>> 'foo bar foo'.numberOfOccurrences('foo')
2
若要获取子字符串的索引,请参见如何查找子字符串的所有出现?。
当前回答
如果你想数整个字符串,这是可行的。
stri_count="If you're looking to count the whole string this can works"
print(len(stri_count))
其他回答
2+其他人已经提供了这个解决方案,我甚至投票了其中一个,但我的可能是新手最容易理解的。
def count_substring(string, sub_string):
slen = len(string)
sslen = len(sub_string)
range_s = slen - sslen + 1
count = 0
for i in range(range_s):
if string[i:i+sslen] == sub_string:
count += 1
return count
这将列出字符串中所有出现的(也是重叠的)并对它们进行计数
def num_occ(str1, str2):
l1, l2 = len(str1), len(str2)
return len([str1[i:i + l2] for i in range(l1 - l2 + 1) if str1[i:i + l2] == str2])
例子:
str1 ='abcabcd'
str2 = 'bc'
将创建这个列表,但只保存BOLD值:
[ab, bc, ca, ab, bc, cd]
返回:
len([bc, bc])
my_string = """Strings are amongst the most popular data types in Python.
We can create the strings by enclosing characters in quotes.
Python treats single quotes the same as double quotes."""
Count = my_string.lower().strip("\n").split(" ").count("string")
Count = my_string.lower().strip("\n").split(" ").count("strings")
print("The number of occurance of word String is : " , Count)
print("The number of occurance of word Strings is : " , Count)
s = 'arunununghhjj'
sb = 'nun'
results = 0
sub_len = len(sb)
for i in range(len(s)):
if s[i:i+sub_len] == sb:
results += 1
print results
根据你的真正意思,我提出以下解决方案:
你的意思是一个空格分隔子字符串的列表,并想知道所有子字符串中的子字符串位置编号是什么: S = 'sub1 sub2 sub3' s.split () .index(“sub2”) > > > 1 你的意思是子字符串在字符串中的char-position: s.find(“sub2”) > > > 5 你的意思是su-bstring的(非重叠)外观计数: s.count(“sub2”) > > > 1 s.count(“子”) > > > 3