이 코드는 작동하지만 여기에서 게시물을 읽으면 매우 "Pythonic"솔루션이 아닐 것이라고 생각합니다. 이 특정 문제를 해결하기위한보다 효율적인 방법이 있습니까?다른 문자열의 문자열을 계산하는 Python의 더 좋은 방법
이 코드가 수행하는 작업 : 다른 문자열에서 발견 된 한 문자열의 인스턴스를 계산하고 그 개수를 반환합니다. 사용자가 빈 문자열을 전달하려고 시도하면 오류가 발생합니다.
내가 함께하지만이 할 수있는 더 좋은 더 효율적으로 더 "파이썬"방법이 있는지 궁금 와서 코드의 버전 :
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
이 코드는 파이썬 2.7로 작성되었지만 3에서 작동한다 .엑스.
가능한 중복 (http://stackoverflow.com/questions/11476713/determining-how-many-times-a-substring-occurs- in-a-string-in-python) – languitar
"duplicate"는 유용한 피드백을 포함하고 있습니다.이 글에 직접 나오는 답변은 "duplicate"스레드에서 찾을 수있는 것보다 더 구체적이고 우수한 해결책입니다. 간단히 말해서, 왜 이것이 속는 사람으로 표시 되었는가를 알 수 있지만, 나는 다른 게시물에서 필요한 답을 얻을 수 없었습니다. 나는 여기에서 희망하고있는 대답을 얻고 있으며,이 실로부터 좋은 것을 배우고있다. – TMWP