python - 让 str.count() 在 python 上工作

标签 python

<分区>

我是编程新手。我一直在努力让 string.count 函数发挥作用。 这是我目前所拥有的:

def trial ():
    a = raw_input ("Enter a string:").lower() 
    print a
    b = raw_input ("Enter a substring:").lower()
    print b

    print "The total character count is:" + a.count('b')

它仍然没有给我计数。它一直给我<built-in method count of str object at 0x0181B500> . 我想我做错了什么。我意识到这可能是一个简单的问题,但我是初学者。我读到你必须使用 str.count (sub[,start[,end]]) 但开始和结束是什么意思?我阅读了描述,但我并没有真正理解它。

任何形式的帮助将不胜感激!

最佳答案

您没有保存您的代码,或者正在使用 print a.count 而不是 print a.count()。前者意味着您正在打印字符串对象中 count 方法的表示,因此打印出:

<built-in method count of str object at 0x0181B500>

至于sub,start,end是什么意思,我可以推荐the Python documentation for string objects?

string.count(s, sub[, start[, end]]) 

Return the number of (non-overlapping) occurrences of substring sub in string s[start:end]. Defaults for start and end and interpretation of negative values are the same as for slices.

本质上,这意味着:

"Some long text right about here".count("o",5,9)

只会计算子字符串 "Some long text right about here"[5:9] 中的 o 的个数,等价于 "long ",因此将返回 1

关于python - 让 str.count() 在 python 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21226188/

相关文章:

python - 使用 context.use_certificate_chain_file 时为 "key values mismatch"

python - 如何通过设置阈值来处理 RASA NLU 中的回退意图

python - unwrap() 后使用 beautifulSoup 获取真实文本

python - 根据纬度/经度和半径选择 geopandas 或 pandas 中的行

python - 在 ipython notebook 中读取输入值

python - 我需要一种快速的方法来循环遍历 Python 中图像/堆栈的像素

python - 使用 PyBombs 安装 gr-gsm

python - 具有自定义属性的 AppEngine bulkloader 导出模型

python - 在保持索引顺序的同时连接两个 Pandas DataFrame

python - 如何在 Python 中获取 unicode 月份名称?