python使用正则化检查字符串的起始和结束字符相同
#python使用正则化检查字符串的起始和结束字符相同
# Python program to check if a string starts# and ends with the same character# import re module as it provides# support for regular expressionsimport re# the regular expressionregex = r'^[a-z]$|^([a-z]).*\1$'# function for checking the stringdef check(string):# pass the regular expression# and the string in the search() methodif(re.search(regex, string)):print("Valid")else:print("Invalid")if __name__ == '__main__' :sample1 = "abba"sample2 = "a"sample3 = "abc"check(sample1)check(sample2)check(sample3)
参考:Python – Check whether a string starts and ends with the same character or not (using Regular Expression)
参考:Python: Check whether a string starts with specified characters
参考:python re