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

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

问题描述

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

a=''打印(len(a))打印(a.count(''))

输出:

<预><代码>01

解决方案

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

<块引用>

返回子串sub不重叠出现的次数.

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

一般来说,空字符串会在给定字符串的所有位置匹配,包括开头和结尾,所以计数应该总是是长度加上1:

<预><代码>>>>(' ' * 100).count('')101

那是因为空字符串被认为存在于一个字符串的所有字符之间;对于长度为 2 的字符串,有 3 个空字符串;一个在开头,一个在两个字符之间,一个在结尾.

所以是的,结果是不同的,它们是完全正确的.

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(''))

Output:

0
1

解决方案

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

Return the number of non-overlapping occurrences of substring sub.

There is exactly one such place where the substring '' occurs in the string '': right at the start. So the count should return 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

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天全站免登陆