gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:01:52 24 4
gpt4 key购买 nike

“ABCDE”没有空字符。但是当我输入时

"" in "ABCDE"

Python 解释器返回 True

为什么?

“ABCDE”中有空字符吗?我不这么认为。

当我使用这些代码时我还发现:

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

它返回 0 而不是 -1

这是为什么?

最佳答案

对于具有字符串对象表示为字符数组的语言背景的人来说,这可能会令人惊讶,但如果我们尝试遵循这样的方法

string = 'ABCDE'
characters_list = list(string)

然后

'' in characters_list

将是False语句。

空字符串可能来自 mathematics ,其中它是 string concatenation 的二元运算的中性元素, 我。 e.对于每个字符串a

a + empty_string == empty_string + a == a

其中+是字符串连接符号。那么“子字符串”可以定义如下:

  • 对于每个字符串ab,我们说ab的子串 当且仅当存在字符串 cd 使得

    b == c + a + d

让我们将 a b 的子字符串表示为 a in b

通过这些空字符串子字符串的定义可以证明引理

  • empty_string 是任意字符串 a 的子字符串:

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

    那么如果我们定义c = empty_stringd = a:

    a == c + empty_string + d

    根据定义a中的empty_string

关于python - 为什么每个字符串都包含空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43729159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com