为什么str.count('')和len(str)给出不同的输出? [英] Why are str.count('') and len(str) giving different output?

查看:103
本文介绍了为什么str.count('')和len(str)给出不同的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看下面的代码,请解释为什么 str.count('')方法和 len(str)函数给出两个不同的输出。

Look at following code and please explain why the str.count('') method and len(str) function is giving two different outputs.

a=''
print(len(a))
print(a.count(''))

输出:

0
1


推荐答案

str.count()计算子字符串的非重叠出现次数:

str.count() counts non-overlapping occurrences of the substring:


返回子字符串 sub 不重复出现的次数。

恰好有一个这样的地方,子字符串''出现在字符串''中:就在开头。因此,计数应该返回 1

There is exactly one such place where the substring '' occurs in the string '': right at the start. So the count should return 1.

通常,空字符串将匹配在给定字符串的所有位置处,包括开始和结束位置,因此计数应始终为长度加上1:

Generally speaking, the empty string will match at all positions in a given string, including right at the start and end, so the count should always be the length plus 1:

>>> (' ' * 100).count('')
101

这是因为空字符串被认为存在于字符串的所有字符之间;对于字符串长度2,有3个空字符串;

That's because empty strings are considered to exist between all the characters of a string; for a string length 2, there are 3 empty strings; one at the start, one between the two characters, and one at the end.

所以是的,结果是不同的,而且完全正确。

So yes, the results are different and they are entirely correct.

这篇关于为什么str.count('')和len(str)给出不同的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆