pythonstartswith是如何工作的? [英] How does python startswith work?

查看:33
本文介绍了pythonstartswith是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<预><代码>>>>"你好".startswith("")真的

文档说明:

<块引用>

如果字符串以前缀开头,则返回True,否则返回False.prefix 也可以是要查找的前缀元组.

那么这个函数是如何工作的?

解决方案

str.startswith() 在 Python 代码中可以表示为:

 def startswith(source, prefix):返回源[:len(prefix)] == 前缀

它测试源字符串的第一个 len(prefix) 字符是否等于前缀.如果传入长度为零的前缀,则意味着测试前 0 个字符.长度为 0 的字符串总是等于任何其他长度为 0 的字符串.

请注意,这也适用于其他字符串测试:

<预><代码>>>>s = 'foobar'>>>'' 在 s真的>>>s.endswith('')真的>>>s.find('')0>>>s.index('')0>>>s.count('')7>>>s.replace('', ' -> ')' ->f->o ->o ->b->->r ->'

最后两个演示,计算空字符串或用其他东西替换空字符串,表明您可以在输入字符串的每个位置找到一个空字符串.

I am not able to understand the behavior of the str.startswith method.

If I execute "hello".startswith("") it returns True. Ideally it doesn't starts with empty string.

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

The documentation states:

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

So how does the function work?

解决方案

str.startswith() can be expressed in Python code as:

 def startswith(source, prefix):
    return source[:len(prefix)] == prefix

It tests if the first len(prefix) characters of the source string are equal to the prefix. If you pass in a prefix of length zero, that means the first 0 characters are tested. A string of length 0 is always equal to any other string of length 0.

Note that this applies to other string tests too:

>>> 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 -> '

Those last two demos, counting the empty string or replacing the empty string with something else, shows that you can find an empty string at every position in the input string.

这篇关于pythonstartswith是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆