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”函数。

  • 如果开头和结尾的字符匹配,则在控制台上显示相关输出。

  • 在控制台外部,定义了一个字符串并显示在控制台上。

  • 定义了一个子字符串并显示在控制台上。

  • 通过将字符串和子字符串传递来调用该方法。

  • 输出显示在控制台上。

更新于: 20-Sep-2021

1K+ 浏览

开启你的 职业

完成课程获得认证

开始
广告
© . All rights reserved.