【问题标题】:Do you know why is the answer 6 for python [closed]你知道为什么 python 的答案是 6 [关闭]
【发布时间】:2017-05-18 09:50:03
【问题描述】:

我是一个绝对的初学者,请求大家帮助大师。 你知道吗,为什么答案是 6(我在 udacity 上运行 python 解释器)

s = 'udacity'
t = 'city'
print s.find(t[i:])

答案:6

【问题讨论】:

  • 什么是i?是 3 还是 -1?你到底想在字符串中找到什么?

标签: python string subsequence pythoninterpreter


【解决方案1】:

您的代码中发生了两件事:

1) 字符串的子字符串(t[i:])
2)查找子字符串/字符第一次出现的索引(s.find())

首先执行t[i:],相当于从第i个(3, i=3)索引中找到t("city")的子串,返回"y"。

0 1 2 3

c 它 y

现在代码变成了 s.find("y"),这意味着在 "s" ("udacity") 中找到 "y" 第一次出现的索引,因此它返回 6。

0 1 2 3 4 5 6

u d a c i t y

【讨论】:

    【解决方案2】:

    因为i 等于 3 => t[i:] 等于 'y' 'udacity''y' 的索引为 6

    【讨论】:

      猜你喜欢
      • 2023-02-21
      • 2022-06-16
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-10
      • 1970-01-01
      相关资源
      最近更新 更多