Python中如何检查字符串的开始和结束

655Z技术栈 Python编程 2026年01月24日 21

Python中有两种方法可以检查字符串的开始和结束:

  1. 使用startswith()和endswith()方法:
s = "Hello, world!" # 检查字符串是否以特定的前缀开始 if s.startswith("Hello"): print("String starts with 'Hello'") # 检查字符串是否以特定的后缀结束 if s.endswith("world!"): print("String ends with 'world!'")
  1. 使用切片:
s = "Hello, world!" # 检查字符串的前几个字符是否与特定字符串相同 if s[:5] == "Hello": print("String starts with 'Hello'") # 检查字符串的最后几个字符是否与特定字符串相同 if s[-6:] == "world!": print("String ends with 'world!'")

这两种方法都可以用来检查字符串的开始和结束,选择其中一种方法即可。

提供PHP及ThinkPHP框架的定制开发、代码优化,PHP修改、ThinkPHP修改。

邮箱:yvsm@163.com 微信:yvsm316 QQ:316430983
关闭

用微信“扫一扫”