在Python中查找子字符串

时间:2014-12-16 17:57:47

标签: python regex

是否有快速和pythonic方法在另一个字符串中搜索字符串,然后将其分配给变量?

到目前为止,我只能获得内部字符串开始的索引:

text = "helothere"
a = text.find('helo')
print a # this prints '0'

6 个答案:

答案 0 :(得分:10)

也许是这样的:

a = 'helo' if 'helo' in text else ''

答案 1 :(得分:2)

为什么不

if text.find(the_string) != -1:
    a = the_string

因为你知道从头开始寻找/分配的字符串。

答案 2 :(得分:1)

这会有用吗?

text = "helothere"
a = "helo"
if a in text:
    print a
else:
    a=''

答案 3 :(得分:1)

你几乎就在那里......因为你已经找到了子串开始的索引,你可以在你使用find找到的起始索引和你之后的子串的长度之间拼接字符串。重新寻找...

text = "helothere"
a = text.find('helo')

# ...

foundStringLength = len('helo')
myResult = text[a:foundStringLength]

print(myResult)

有很多更好的方法可以做到这一点,但我想我会发布一个替代已经说过的内容。

更一般的版本:

myTextToSearch = "" # define the string to search, through a function arg or something
mySubstringToSearchFor = "" # same deal here
searchStringLength = len(mySubstringToSearchFor)

startIndex = myTextToSearch.find(mySubstringToSearchFor)

if startIndex == -1:
    pass # didn't find the substring... return False/None/etc.
else:
    myResult = myTextToSearch[startIndex:searchStringLength]

    # now do stuff with the result!
    print(myResult)
    return myResult
祝你好运!

答案 4 :(得分:1)

不确定您实际上想要的是什么,但这会解决您的问题吗?

text = "helothere"
term = "helo"

a = term if term in text else 'Term not in text'

您可以将else分配给您想要的任何内容。

答案 5 :(得分:1)

您可以编写一个函数来执行此操作:

def find_text(text, s):
    return text if text in s else None

text = "helothere"
print find_text("helo", text)  # --> helo
print find_text("not", text)   # --> None