Python - 檢查字串是否以相同字元開頭和結尾
當需要檢查一個字串是否以相同字元開始和結束時,可以使用正則表示式。可以定義一個方法,該方法使用“search”函式檢視字串是否以一個特定字元開始和結束。
示例
下面是對此的演示
import re
regex_expression = r'^[a-z]$|^([a-z]).*\1$'
def check_string(my_string):
if(re.search(regex_expression, my_string)):
print("The given string starts and ends with the same character")
else:
print("The given string doesnot start and end with the same character")
my_string = "abcbabda"
print("The string is:")
print(my_string)
check_string(my_string)輸出
The string is: abcbabda The given string starts and ends with the same character
說明
匯入了所需的包。
定義了一個名為“check_string”的方法,它將字串作為引數。
透過將字串和正則表示式作為引數傳遞來呼叫“search”函式。
如果開頭和結尾的字元匹配,則在控制檯上顯示相關輸出。
在控制檯外部,定義了一個字串並顯示在控制檯上。
定義了一個子字串並顯示在控制檯上。
透過將字串和子字串傳遞來呼叫該方法。
輸出顯示在控制檯上。
廣告
資料結構
聯網
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP