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

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

使用startswith()和endswith()方法:

s = "Hello, world!"

# 检查字符串是否以特定的前缀开始
if s.startswith("Hello"):
    print("String starts with 'Hello'")

# 检查字符串是否以特定的后缀结束
if s.endswith("world!"):
    print("String ends with 'world!'")

使用切片:

s = "Hello, world!"

# 检查字符串的前几个字符是否与特定字符串相同
if s[:5] == "Hello":
    print("String starts with 'Hello'")

# 检查字符串的最后几个字符是否与特定字符串相同
if s[-6:] == "world!":
    print("String ends with 'world!'")

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

阅读剩余
THE END