在Python 3.x中寻找功能

2024-05-15 04:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

当我们有以下情况时:

tweet2 = 'Want cheap snacks? Visit @cssu office in BA2283'

print(tweet2[tweet2.find('cheap')])结果是输出'c',我不知道它是如何做到这一点的。我试了一下可视化工具,结果什么也没显示出来。谁能解释一下吗?在


Tags: 工具in可视化情况visitfindprintoffice
3条回答

您应该考虑阅读关于字符串方法和列表的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(str,string)方法确定str是出现在string中,还是出现在string的子字符串中,并返回第一次出现的位置。因此,当你调用tweet2.find('cheap')时,它将返回位置,这是廉价的第一次出现。在

{c>在索引的开头返回

相关问题 更多 >

    热门问题