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

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

问题描述

这是一个简短的例子,但很烦人。我知道我可以计算一个字符串在另一个这样的字符串中出现的次数:

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

表示香蕉包含字母 a 3次。

在这里

我的第一个困惑是-当我执行'foo'.count('')时,

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

'' == None ==什么吗?

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?

始终比字母数量高1的字符串包含什么?

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

编辑:'字符两次看起来像一个 字符。我在这里说两次'以避免混淆

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.

推荐答案

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

Every string1 can be thought of as:

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

其中包含 len (any_string)+ 1个''实例。

对于 foo ,例如:

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

可以看到,有 4 个实例 在中。

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?

此答案试图解释Python使用的约定并不打算暗示这是所有语言都采用的方式\应该这样做; 这就是Python的工作方式。

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.

1 Empty字符串是一个例外,并且处理方式不同;他们只是返回 1 ;这又是另一个约定。

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

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

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