这段代码可以工作,但阅读这里的帖子,我得到的印象是它可能不是一个非常"Pythonic“的解决方案。有没有更好更有效的方法来解决这个特定的问题:
这段代码的作用:它计算在一个字符串中找到的另一个字符串的实例,并返回计数。如果用户试图传入空字符串,则会引发错误。
我想出的代码版本,但想知道是否有更好、更有效、更"Pythonic“的方法来做到这一点:
def count_string(raw_string, string_to_count):
if len(string_to_count) == 0:
raise ValueError("The length of string_to_count should not be 0!")
else:
str_count = 0
string_to_count = string_to_count.lower()
raw_string = raw_string.lower()
if string_to_count not in raw_string:
# this causes early exit if string not found at all
return str_count
else:
while raw_string.find(string_to_count) != -1:
indx = raw_string.find(string_to_count)
str_count += 1
raw_string = raw_string[(indx+1): ]
return str_count这段代码是用Python2.7编写的,但应该可以在3.x中运行。
发布于 2017-03-13 22:23:11
为什么不使用str的count方法
>>> a = "abcghabchjlababc"
>>> a.count("abc")
3发布于 2017-03-13 22:26:19
另一种可能的解决方案。
>>> a= 'almforeachalmwhilealmleandroalmalmalm'
>>> len(a.split('alm')) - 1
6
>>> q = "abcghabchjlababc"
>>> len(q.split("abc")) - 1
3https://stackoverflow.com/questions/42765930
复制相似问题