【问题标题】:How to find the number value set to a specific character within a string (without counting) in python [duplicate]如何在python中找到设置为字符串中特定字符(不计算)的数值[重复]
【发布时间】:2014-02-06 01:12:11
【问题描述】:

我最近有一个项目,我需要找到用户输入的字符串中出现特定字符的所有索引。 例如,用户输入字符串“这是一个测试”,我想找到字符串中所有 t 的索引,我会得到 0、11、14 我查看了内置命令,但找不到任何东西,所以知道找到它的方法会很有帮助。

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    使用enumerate 和列表理解:

    st="This is a test"
    
    print([i for i, c in enumerate(st) if c.lower()=='t'])
    

    或者:

    print([i for i, c in enumerate(st) if c in 'tT'])
    

    在任何一种情况下,打印:

    [0, 10, 13]
    

    解释

    “使这项工作”的第一件事是字符串在 Python 中是可迭代的:

    >>> st="This is a test"
    >>> for c in st:
    ...    print c
    ... 
    T
    h
    i
    s
    
    i
    s
    
    a
    
    t
    e
    s
    t
    

    使这项工作的第二件事是枚举,它将字符串中所有字符的计数添加为一个元组:

    >>> for tup in enumerate(st):
    ...    print tup
    ... 
    (0, 'T')
    (1, 'h')
    (2, 'i')
    (3, 's')
    (4, ' ')
    (5, 'i')
    (6, 's')
    (7, ' ')
    (8, 'a')
    (9, ' ')
    (10, 't')
    (11, 'e')
    (12, 's')
    (13, 't')
    

    将这两个概念放在一个列表推导中会产生结果:

    [i for i, c in enumerate(st) if c.lower()=='t']
                     ^^^                               Produces the tuple of index and character
           ^  ^                                        Index, Character
                                      ^^^^^^^^^^^      test the character if it is 't'
     ^                                                 What is wanted - list of indices
    

    【讨论】:

    • 谢谢你帮了大忙。
    • 谢谢你这个作品,你能解释一下它为什么起作用吗,我想了解代码背后的工作原理
    【解决方案2】:

    只是一种直接的方法作为(更好的)enumerate 选项的替代方案:

    [range(len(st))[i] for i in range(len(st)) if st[i].lower() == 't']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-24
      • 1970-01-01
      • 2020-09-09
      • 2020-04-09
      • 2018-04-14
      • 2016-05-20
      • 1970-01-01
      • 2022-06-17
      相关资源
      最近更新 更多