接受以字母数字字符结尾的字符串的 Python 程序
pythonserver side programmingprogramming更新于 2025/11/8 6:36:17
当需要检查字符串是否以字母数字字符结尾时,使用正则表达式。定义了一种方法来检查字母数字字符,并返回字符串作为输出。
示例
下面是相同的演示
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’方法并检查字符串是否以特定字符结尾。
在方法外部,定义字符串并显示在控制台上。
通过传递此字符串来调用该方法。
输出显示在控制台上。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

