[英]Find function in Python 3.x
When we have the following: 当我们具有以下条件时:
tweet2 = 'Want cheap snacks? Visit @cssu office in BA2283'
print(tweet2[tweet2.find('cheap')])
results in the output 'c'
and I cant wrap my head around how it does this. print(tweet2[tweet2.find('cheap')])
的输出结果为'c'
,我无法理解它是如何做到的。 I tried the visualizer and it didn't show anything. 我尝试了可视化器,但没有显示任何内容。 Could anyone please explain?
有人可以解释吗?
tweet2.find('cheap')
返回找到“ cheap”开头的索引,并且在tweet2[index]
使用该tweet2[index]
,它返回该索引处的字符,即“ c”
It's because the find(str, string) method determines if str occurs in string, or in a substring of string and returns the position of first occurrence. 这是因为find(str,string)方法确定str是出现在字符串中还是出现在字符串的子字符串中,并返回第一次出现的位置。 So when you call
tweet2.find('cheap')
it will return the position that is the first occurs of cheap. 因此,当您调用
tweet2.find('cheap')
,它将返回便宜的第一次出现的头寸 。
You should consider reading python documentation on string methods and lists 您应该考虑阅读有关字符串方法和列表的python文档
# define string variable tweet2
tweet2 = 'Want cheap snacks? Visit @cssu office in BA2283'
# find position of substring 'cheap', which is 5 (strings has 0-based indices in python
n = tweet2.find('cheap')
# print 5th element of string, which is 'c'
print(tweet2[n])
find
returns an index, not a slice. find
返回一个索引,而不是切片。
If you want the full string you can get it like so: 如果您需要完整的字符串,可以这样获取:
to_find = 'cheap'
ind = tweet2.find(to_find)
print(tweet2[ind:ind+len(to_find)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.