获取数据的原因是什么。计数(“and”)为2?

2024-05-14 19:57:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在执行下面的代码时,我得到的结果是2。有人能告诉我在python3x中得到2的原因吗

data="Hands to clap and eyes to see"
data.count("and")

二,


Tags: andto代码datacount原因seeeyes
1条回答
网友
1楼 · 发布于 2024-05-14 19:57:52

从文档: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

要解决这个问题,您可以将字符串拆分为list,然后应用count,它将只匹配像and这样的完整单词,而不匹配像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

相关问题 更多 >

    热门问题