如果我知道我可以找到一个字符串的开头和结尾,我怎么能删掉一段字符串呢?

How would I be able to cut out a section of a string if I know I can find both the beginning and the end of a string?

我正在尝试查找字符串的开头和结尾,然后使用该信息将字符串的中间部分存储到变量中。

但是,我不确定为什么第一个 if 语句没有通过。见下文:

str = "start_message_end"

# QUESTION: Why does this test below not pass?
if str.find("start_"):
    print "Found the start"

# This works fine
if str.find("_end"):
    print "Found the end"

# This was just another test
if str.find("message"):
    print "Found the message"

因为str.findreturns索引:

>>> "start_message_end".find("start_")
0

在布尔上下文中,0 的计算结果为 False:

>>> bool(0)
False

相反,我认为你想要 str.startswith:

>>> "start_message_end".startswith("start_")
True

然后您可以使用切片(参见 the tutorial)来提取字符串的中间部分:

>>> s = "start_message_end"
>>> if s.startswith("start_") and s.endswith("_end"):
    print s[6:-4]


message