python - python 的startswith 是如何工作的?

标签 python string

我无法理解 str.startswith 的行为方法。

如果我执行"hello".startswith(""),它会返回True。理想情况下它不以空字符串开头。

>>> "hello".startswith("")
True

文档指出:

Return True if string starts with the prefix, otherwise return False. 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/

相关文章:

python - cv2.imshow 崩溃 - libc++abi.dylib : terminating with uncaught exception of type NSException

python - Tornado模板和Jinja2的区别

python - 从 Visual C++ 代码运行 Python(嵌入式 Python)

PHP 转义一个字符串,如果它还没有被实体转义的话

javascript - python websocket 握手 (RFC 6455)

python - 为什么这个 lambda 操作不起作用?

php - 使用php删除字符串中的未知字符

c - 区分字符串和字节数组?

java - 检查 String 数组元素是否为 null

python - 正则表达式匹配 Ph.D 和 ph.d