gpt4 book ai didi

python - 查找字符串是否以相同的单词开头和结尾

转载 作者:太空狗 更新时间:2023-10-30 01:42:11 31 4
gpt4 key购买 nike

我正在尝试检查字符串是否以同一个词开头和结尾。例如地球

s=raw_input();
m=re.search(r"^(earth).*(earth)$",s)
if m is not None:
print "found"

我的问题是字符串只包含一个单词 例如:earth

目前我已经硬编码了这个案例

if m is not None or s=='earth':
print "found"

还有其他方法吗?

编辑:

字符串中的单词由空格分隔。寻找正则表达式解决方案

一些例子:

"earth is earth","earth", --> 有效

"earthearth", "eartheeearth", "earth earth mars"--> 无效

最佳答案

使用 str.startswithstr.endswith方法代替。

>>> 'earth'.startswith('earth')
True
>>> 'earth'.endswith('earth')
True

您可以简单地将它们组合成一个函数:

def startsandendswith(main_str):
return main_str.startswith(check_str) and main_str.endswith(check_str)

现在我们可以调用它了:

>>> startsandendswith('earth', 'earth')
True

但是,如果代码匹配单词而不是单词的一部分,拆分字符串可能更简单,然后检查第一个和最后一个单词是否是您要检查的字符串:

def startsandendswith(main_str, check_str):
if not main_str: # guard against empty strings
return False
words = main_str.split(' ') # use main_str.split() to split on any whitespace
return words[0] == words[-1] == check_str

运行它:

>>> startsandendswith('earth', 'earth')
True
>>> startsandendswith('earth is earth', 'earth')
True
>>> startsandendswith('earthis earth', 'earth')
False

关于python - 查找字符串是否以相同的单词开头和结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17389109/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com