[英]string.find indexing in Python
I'm trying to understand why the following python code incorrectly returns the string "dining": 我试图理解为什么以下python代码错误地返回字符串“ dining”:
def remove(somestring, sub):
"""Return somestring with sub removed."""
location = somestring.find(sub)
length = len(sub)
part_before = somestring[:location]
part_after = somestring[location + length:]
return part_before + part_after
print remove('ding', 'do')
I realize the way to make the code run correctly is to add an if statement so that if the location variable returns a -1 it will simply return the original string (in this case "ding"). 我意识到使代码正确运行的方法是添加一个if语句,以便如果location变量返回-1,则它只会返回原始字符串(在这种情况下为“ ding”)。 The code, for example, should be: 例如,代码应为:
def remove(somestring, sub):
"""Return somestring with sub removed."""
location = somestring.find(sub)
if location == -1:
return somestring
length = len(sub)
part_before = somestring[:location]
part_after = somestring[location + length:]
return part_before + part_after
print remove('ding', 'do')
Without using the if statement to fix the function, the part_before variable will return the string "din". 在不使用if语句修复函数的情况下,part_before变量将返回字符串“ din”。 I would love to know why this happens. 我很想知道为什么会这样。 Reading the python documentation on string.find (which is ultimately how part_before is formulated) I see that the location variable would become a -1 because "do" is NOT found. 阅读关于string.find的python文档(这最终是part_before公式的方式),我发现位置变量将变为-1,因为未找到“ do”。 But if the part_before variable holds all letters before the -1 index, shouldn't it be blank and not "din"? 但是,如果part_before变量包含-1索引之前的所有字母,那么它不应该为空而不是“ din”吗? What am I missing here? 我在这里想念什么?
For reference, Python documentation for string.find states: 作为参考,关于string.find的Python文档指出:
string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. 返回s中找到子字符串sub的最低索引,以使sub完全包含在s [start:end]中。 Return -1 on failure. 失败时返回-1。 Defaults for start and end and interpretation of negative values is the same as for slices. 开始和结束以及负值的解释的默认值与切片相同。
string = 'ding'
string[:-1]
>>> 'din'
Using a negative number as an index in python returns the n th element from the right-hand side. 在Python中使用负数作为索引会从右侧返回第n个元素。 Accordingly, a slice with :-1
return all but the last element of the string. 因此,带有:-1
的slice返回字符串的最后一个元素以外的所有元素。
If you have a string 'ding'
and you are searching for 'do'
, str.find()
will return -1. 如果您有字符串'ding'
并且正在搜索'do'
,则str.find()
将返回-1。 'ding'[:-1]
is equal to 'din'
and 'ding'[-1 + len(sub):]
equals 'ding'[1:]
which is equal to 'ing'
. 'ding'[:-1]
等于'din'
, 'ding'[-1 + len(sub):]
等于'ding'[1:]
,等于'ing'
。 Putting the two together results in 'dining'. 将两者放在一起将导致“用餐”。 To get the right answer, try something like this: 为了获得正确的答案,请尝试如下操作:
def remove(string, sub):
index = string.find(sub)
if index == -1:
return string
else:
return string[:index] + string[index + len(sub):]
The reason that string[:-1]
is not equal to the whole string is that in slicing, the first number (in this case blank so equal to None
, or for our purposes equivalent to 0) is inclusive, but the second number (-1) is exclusive. string[:-1]
不等于整个字符串的原因是,在切片时,第一个数字(在本例中为空白,因此等于None
,或者对于我们而言等于0)包括在内,但是第二个数字( -1)是排他性的。 string[-1]
is the last character, so that character is not included. string[-1]
是最后一个字符,因此不包括该字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.