Python 程式接受以字母數字字元結尾的字串
當需要檢查字串是否以字母數字字元結尾時,可以使用正則表示式。我們定義了一個方法來檢查字母數字字元,並返回字串作為輸出。
示例
以下是對上文的展示
import re
regex_expression = '[a-zA-z0-9]$'
def check_string(my_string):
if(re.search(regex_expression, my_string)):
print("The string ends with alphanumeric character")
else:
print("The string doesnot end with alphanumeric character")
my_string_1 = "Python@"
print("The string is :")
print(my_string_1)
check_string(my_string_1)
my_string_2 = "Python1245"
print("\nThe string is :")
print(my_string_2)
check_string(my_string_2)輸出
The string is : Python@ The string doesn’t end with alphanumeric character The string is : Python1245 The string ends with alphanumeric character
說明
匯入所需的包。
定義正則表示式字串。
定義名為“check_string”的方法,它將字串作為引數。
呼叫“search”方法,並檢查字串是否以特定字元結尾。
在此方法外部,定義字串並將其顯示在控制檯上。
透過傳入此字串來呼叫該方法。
輸出顯示在控制檯上。
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP