我无法理解 str.startswith
的行为方法。
如果我执行"hello".startswith("")
,它会返回True。理想情况下它不以空字符串开头。
>>> "hello".startswith("")
True
文档指出:
Return
True
if string starts with the prefix, otherwise returnFalse
.prefix
can also be a tuple of prefixes to look for.
那么这个函数是如何工作的呢?
最佳答案
str.startswith()
可以用 Python 代码表示为:
def startswith(source, prefix):
return source[:len(prefix)] == prefix
它测试源字符串的前 len(prefix)
字符是否等于前缀。如果传入长度为零的前缀,则意味着测试前 0 个字符。长度为 0 的字符串始终等于任何其他长度为 0 的字符串。
请注意,这也适用于其他字符串测试:
>>> s = 'foobar'
>>> '' in s
True
>>> s.endswith('')
True
>>> s.find('')
0
>>> s.index('')
0
>>> s.count('')
7
>>> s.replace('', ' -> ')
' -> f -> o -> o -> b -> a -> r -> '
最后两个演示,计算空字符串或用其他内容替换空字符串,表明您可以在输入字符串中的每个位置找到空字符串。
关于python - python 的startswith 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41079054/