2024-05-14 19:57:52 发布
网友
在执行下面的代码时,我得到的结果是2。有人能告诉我在python3x中得到2的原因吗
data="Hands to clap and eyes to see" data.count("and")
二,
从文档:https://docs.python.org/3/library/stdtypes.html#str.count
str.count(sub[, start[, end]]) Return the number of non-overlapping occurrences of substring sub in the range [start, end].
如您所见,字符串Hands to clap and eyes to see有两个and字符串,一个在Hands中,一个在and中,因此计数为2
Hands to clap and eyes to see
and
Hands
要解决这个问题,您可以将字符串拆分为list,然后应用count,它将只匹配像and这样的完整单词,而不匹配像hands这样的部分单词
hands
In [115]: data="Hands to clap and eyes to see" #Split on whitespace to convert string to list of words In [116]: li = data.split() #Find the complete word and in the list In [117]: li.count('and') Out[117]: 1
从文档:https://docs.python.org/3/library/stdtypes.html#str.count
如您所见,字符串
Hands to clap and eyes to see
有两个and
字符串,一个在Hands
中,一个在and
中,因此计数为2要解决这个问题,您可以将字符串拆分为list,然后应用count,它将只匹配像
and
这样的完整单词,而不匹配像hands
这样的部分单词相关问题 更多 >
编程相关推荐