为什么“test".count('') 返回 5? [英] Why does "test".count('') return 5?

查看:12
本文介绍了为什么“test".count('') 返回 5?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一篇简短的文章,但非常令人恼火.我知道我可以像这样计算一个字符串在另一个字符串中出现的次数:

'banana'.count('a')>>>3

意味着 banana 包含字母 "a" 3 次.

这就是它变得有点奇怪的地方.

我的第一个困惑是 - 当我执行 'foo'.count('') 时,Python 在寻找什么?

'' == None == 什么?

情况似乎并非如此,但话说回来,从逻辑上讲,'' 是什么?更重要的是,为什么

'test'.count('')>>>5

返回比字符串长度多一的?

总是比字母数量高 1 的字符串中到底包含了什么?虚空?

' 字符两次看起来像一个 " 字符.我在这里谈论两次 ' 以避免混淆>

关于 '' 的数量如何发生似乎有些混乱.请参阅下面的评论.

解决方案

每个字符串1 可以认为是:

any_string = "" + "".join(any_string) + ""

其中正好包含 len(any_string) + 1'' 实例.

<小时>

例如,对于 "foo",它将是:

"" + "f" + "" + "o" + "" + "o"+ ""# |----- 来自加入 -------|

正如可以看到的那样,它有 4"" in 实例.

<小时>

但是请注意,这是一个没有答案或所有答案可以以某种方式支持自己案例的问题.这很哲学:

  • 虚无中包含多少虚无?
  • 有多少东西没有被包含?

这个答案试图解释 Python 使用的约定,并不打算暗示这是所有语言都应该这样做的方式;Python 就是这样做的.

<小时>

1空字符串是一个例外,处理方式不同;他们只是返回1;这是另一个约定.

This is a short one, yet very irritating. I know I can count the amount of times a string occurs within another string like this:

'banana'.count('a')
>>>3

meaning that banana contains the letter "a" 3 times.

This is where it gets kind of weird.

My first confusion is - when I do 'foo'.count(''), what does Python look for?

is '' == None == anything?

It doesn't seem to be the case, but then again, what IS '' logically speaking? And more importantly, why does

'test'.count('')
>>>5

return one more than the length of the string?

What the hell is included in a string that's always 1 higher than the amount of letters? the void?

EDIT: the ' character twice looks like one " character. I am talking about two times ' here, to avoid confusion

EDIT2: There seems to be some confusion about how the amount of '' happen. Refer to comments below.

解决方案

Every string1 can be thought of as:

any_string = "" + "".join(any_string) + ""

which contains exactly len(any_string) + 1 instances of ''.


For "foo" for example, it would be:

"" + "f" + "" + "o" + "" + "o"+ ""
#    |----- from join -------|

As it can be seen there are 4 instances of "" in it.


Note however, that this is a problem where no answer or all answers could somehow support a case for themselves. It get's philosophical:

  • How much nothing is contained in nothing?
  • How much nothing is contained in something?

This answer tries to explain the convention used by Python and does not intend to suggest that this is the way all languages do it should be doing it; it is just how Python does it.


1Empty strings are an exception and are handled differently; they simply return 1; which is yet another convention.

这篇关于为什么“test".count('') 返回 5?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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