【问题标题】:The opposite to index()?与 index() 相反?
【发布时间】:2016-02-24 06:48:51
【问题描述】:

如果我要写以下内容:

s = 'abcdefh'
print s.index(c)

我会得到 2。但是,我想做相反的事情,即知道索引号并打印相应的字母(换句话说,我知道索引号 2 并希望打印字母“c”)。

【问题讨论】:

  • 先看教程(docs.python.org/3.5/tutorial),再提问...
  • 看起来很简单:next(char for index, char in enumerate(s) if index == 2) ;-)

标签: python indexing


【解决方案1】:

该操作称为索引。这就是为什么s.index() 被称为s.index()。

print s[2]

【讨论】:

    【解决方案2】:

    index 的反面是使用[] 运算符:

    >>> s = 'abcdefh'
    >>> s[2]
    'c'
    

    【讨论】:

      猜你喜欢
      • 2018-12-13
      • 2013-04-23
      • 1970-01-01
      • 2021-08-02
      • 2023-03-07
      • 2014-02-15
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多