How to find the count of a word in a string?

后端 未结 9 954
北恋
北恋 2020-12-01 13:07

I have a string \"Hello I am going to I with hello am\". I want to find how many times a word occur in the string. Example hello occurs 2 time. I tried this app

9条回答
  •  猫巷女王i
    2020-12-01 13:25

    Here is an alternative, case-insensitive, approach

    sum(1 for w in s.lower().split() if w == 'Hello'.lower())
    2
    

    It matches by converting the string and target into lower-case.

    ps: Takes care of the "am ham".count("am") == 2 problem with str.count() pointed out by @DSM below too :)

提交回复
热议问题