浅谈 Python startswith/endswith 实现原理

AI悦创原创2022年9月6日
大约 2 分钟

你好,我是悦创。

废话少说,直接上代码。

In [1]: s = "aiyuechuang"

In [2]: s.startswith("ai")
Out[2]: True

In [3]: s.startswith("a")
Out[3]: True

In [4]: s.startswith("a000ss")
Out[4]: False

In [5]: s.endswith("hjb")
Out[5]: False

In [6]: s.endswith("g")
Out[6]: True

In [7]: s.endswith("og")
Out[7]: False

In [8]: s.endswith("ng")
Out[8]: True

简单实现:

In [9]: a = "ai"

In [10]: length = len(a)

In [11]: s = "aiyuechuang"

In [12]: if a == s[:length]:
    ...:     print("Suc")
    ...: else:
    ...:     print("Faild")
    ...:
Suc
In [16]: a = "aiyppp"

In [17]: if a == s[:length]:
    ...:     print("Suc")
    ...: else:
    ...:     print("Faild")
    ...:
Faild

In [18]: a = "aiypppslslslsllsl"

In [19]: length = len(a)

In [20]: if a == s[:length]:
    ...:     print("Suc")
    ...: else:
    ...:     print("Faild")
    ...:
Faild

In [21]: a = "aiypppslslslsllsl"

In [22]: if a == s[:len(a)]:
    ...:     print("Suc")
    ...: else:
    ...:     print("Faild")
    ...:
Faild

In [23]: "aiyc"[-1:-2]
Out[23]: ''

In [24]: "aiyc"[-1:-2:-1]
Out[24]: 'c'

In [25]: "aiyc"[-1:-3:-1]
Out[25]: 'cy'

In [26]: "aiyc"[:-3:-1]
Out[26]: 'cy'

In [27]: "aiyc"[:-3:-1][::-1]
Out[27]: 'yc'

In [28]: s = "believes"

In [29]: es
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [29], in <cell line: 1>()
----> 1 es

NameError: name 'es' is not defined

In [30]: s = "believes"

In [31]: s[:-2]
Out[31]: 'believ'

In [32]: s[:-1]
Out[32]: 'believe'

In [33]:

欢迎关注我公众号:AI悦创,有更多更好玩的等你发现!

公众号:AI悦创【二维码】

AI悦创·编程一对一

AI悦创·推出辅导班啦,包括「Python 语言辅导班、C++ 辅导班、java 辅导班、算法/数据结构辅导班、少儿编程、pygame 游戏开发」,全部都是一对一教学:一对一辅导 + 一对一答疑 + 布置作业 + 项目实践等。当然,还有线下线上摄影课程、Photoshop、Premiere 一对一教学、QQ、微信在线,随时响应!微信:Jiabcdefh

C++ 信息奥赛题解,长期更新!长期招收一对一中小学信息奥赛集训,莆田、厦门地区有机会线下上门,其他地区线上。微信:Jiabcdefh

方法一:QQopen in new window

方法二:微信:Jiabcdefh