[英]Is there a way to tell if a string slice is in another string in Python?
我正在做一个更大的项目,但我遇到了一个问题,我从字符串中取出一个切片,我试图判断切片是否在主字符串中。 问题是即使类型相同,“in”运算符和“index”运算符似乎也不适用于切片。 有没有办法判断切片是否包含在“主字符串”中,或者您不能以这种方式比较切片和字符串? 这是我要完成的一些示例代码:
x = ['dog']
value = 'dog'
y = 'All values with: ' + value
searchvalue = y[16:]
for i in x:
if searchvalue in i:
print('Is in')
else:
print('Not in')
因此,我希望能够判断从 'y' 中提取的值 'dog' 在 'x' 中。 我觉得它应该很简单,但到目前为止我已经走到了死胡同。
你真的应该考虑使用regex
:
import re
foo = 'some random string'
found = re.match(foo[:3], foo)
如果没有找到,它将返回None
。
您正在尝试查找dog
而不是dog
将 searchvalue 更改为此
searchvalue = y[17:]
您的代码中的问题是索引号。 使用17
或searchvalue.strip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.