“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
其中+
是字符串连接符号。那么“子字符串”可以定义如下:
对于每个字符串
a
、b
,我们说a
是b的子串
当且仅当存在字符串c
、d
使得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_string
和d = a
:a == c + empty_string + d
根据定义
a中的empty_string
。
关于python - 为什么每个字符串都包含空字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43729159/