简体   繁体   English

为什么每个字符串都包含空字符串?

[英]Why does every string contain the empty string?

"ABCDE" has no empty character. “ABCDE”没有空字符。 But when I type但是当我输入

"" in "ABCDE"

Python interpreter returns True . Python 解释器返回True

Why?为什么?

is there any empty character in "ABCDE"? “ABCDE”中有空字符吗? I don't think so.我不这么认为。

And I also found when I use these code:当我使用这些代码时,我还发现:

target = ''
src = 'ABCDE'
src.find(target)

it returns 0 instead of -1它返回 0 而不是 -1

Why is this?为什么是这样?

For people with background in languages where string objects represented as arrays of characters it may be surprising, but if we try to follow such approach like对于具有字符串对象表示为字符数组的语言背景的人来说,这可能会令人惊讶,但如果我们尝试遵循这样的方法

string = 'ABCDE'
characters_list = list(string)

then然后

'' in characters_list

will be False statement.将是False陈述。

Empty string probably came from mathematics , where it is a neutral element for binary operation of string concatenation , ie for every string a空字符串可能来自数学,它是字符串连接的二元运算的中性元素,即对于每个字符串a

a + empty_string == empty_string + a == a

where + is a string concatenation symbol.其中+是字符串连接符号。 Then " substringing " can be defined as follows:那么“子串”可以定义如下:

  • for every strings a , b we say a is substring of b iff exists strings c , d such that对于每个字符串a , b我们说ab子字符串,如果存在字符串c , d使得

    b == c + a + d

Let's denote a is substring of b as a in b .让我们将ab子串表示为a in b

With these definitions of empty string and substringing relation can be proved lemma有了这些空串子串关系的定义,就可以证明引理

  • empty_string is a substring of any string a : empty_string是任何字符串a的子字符串:

     a == (definition of empty_string) == empty_string + a == == (definition of empty_string) == empty_string + empty_string + a

    then if we define c = empty_string and d = a :那么如果我们定义c = empty_stringd = a

     a == c + empty_string + d

    and by definition empty_string in a .根据定义, empty_string in a

Here's a qualitative way to think about it.这是一种定性的思考方式。 Consider the following:考虑以下:

>>> "foo"[0:0]
''

Doing a zero-width slice of a string returns '' .对字符串执行零宽度切片返回'' So, if you can get '' out of a string, it must be in the string and therefore '' in "foo" must be true.因此,如果您可以从字符串中取出'' ,则它必须字符串中,因此'' in "foo"必须为真。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM