Python中有两种方法可以检查字符串的开始和结束:
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!'")
这两种方法都可以用来检查字符串的开始和结束,选择其中一种方法即可。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>