溫馨提示×

Python中如何檢查字符串的開始和結束

小億
205
2024-04-02 17:59:03
欄目: 編程語言

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!'")

這兩種方法都可以用來檢查字符串的開始和結束,選擇其中一種方法即可。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女