简体   繁体   English

有没有办法判断一个字符串切片是否在 Python 中的另一个字符串中?

[英]Is there a way to tell if a string slice is in another string in Python?

I am working on a larger project but I've arrived at an issue where I am taking a slice from a string and I am attempting to tell if the slice is in a main string.我正在做一个更大的项目,但我遇到了一个问题,我从字符串中取出一个切片,我试图判断切片是否在主字符串中。 The problem is that even though the types are the same it seems that the 'in' operator and 'index' operators don't work with the slice.问题是即使类型相同,“in”运算符和“index”运算符似乎也不适用于切片。 Is there a way to tell if a slice is contained in a 'main string' or can you not compare slices and strings in that way?有没有办法判断切片是否包含在“主字符串”中,或者您不能以这种方式比较切片和字符串? Here is some example code on what I am trying to accomplish:这是我要完成的一些示例代码:

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')

So I want to be able to tell that the value 'dog' taken as a slice from 'y' is in 'x'.因此,我希望能够判断从 'y' 中提取的值 'dog' 在 'x' 中。 I fee like it should be simple but I've come to a dead end so far.我觉得它应该很简单,但到目前为止我已经走到了死胡同。

You should really consider using regex :你真的应该考虑使用regex

import re                                                                                                                                                                                                  
foo = 'some random string'                                                                                                                                                                                 
found = re.match(foo[:3], foo)

It will return None if not found.如果没有找到,它将返回None

You are trying to find dog instead of dog Change searchvalue to this您正在尝试查找dog而不是dog将 searchvalue 更改为此

searchvalue = y[17:]

The problem in your code is the index number.您的代码中的问题是索引号。 Use 17 or searchvalue.strip()使用17searchvalue.strip()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM