首页 文章

如何在Python中获取角色的位置?

提问于
浏览
406

如何在python中获取字符串中字符的位置?

8 回答

  • 77

    仅为了完整起见,如果您需要在字符串中查找字符的所有位置,您可以执行以下操作:

    s = 'shak#spea#e'
    c = '#'
    print [pos for pos, char in enumerate(s) if char == c]
    

    将返回 [4, 9]

  • 42
    string.find(character)  
    string.index(character)
    

    也许你想看一下the documentation来找出两者之间的区别 .

  • 11

    只是为了完成,如果我想在文件名中找到扩展名以便检查它,我需要找到最后的' . ',在这种情况下使用rfind:

    path = 'toto.titi.tata..xls'
    path.find('.')
    4
    path.rfind('.')
    15
    

    在我的情况下,我使用以下,无论完整的文件名是什么:

    filename_without_extension = complete_name[:complete_name.rfind('.')]
    
  • 0

    有两种字符串方法, find()index() . 两者之间的差异是找不到搜索字符串时发生的情况 . find() 返回 -1index() 引发 ValueError .

    使用find()

    >>> myString = 'Position of a character'
    >>> myString.find('s')
    2
    >>> myString.find('x')
    -1
    

    使用索引()

    >>> myString = 'Position of a character'
    >>> myString.index('s')
    2
    >>> myString.index('x')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: substring not found
    

    来自Python手册

    string.find(s,sub [,start [,end]])返回s中找到子字符串sub的最低索引,使得sub完全包含在s [start:end]中 . 失败时返回-1 . 开始和结束的默认值以及负值的解释与切片的默认值相同 .

    和:

    string.index(s,sub [,start [,end]])与find()类似,但在找不到子字符串时引发ValueError .

  • 530

    字符可能在字符串中出现多次 . 例如,在字符串 sentence 中, e 的位置是 1, 4, 7 (因为索引通常从零开始) . 但我发现的是 find()index() 两个函数都返回一个字符的第一个位置 . 所以,这可以解决这个问题:

    def charposition(string, char):
        pos = [] #list to store positions for each 'char' in 'string'
        for n in range(len(string)):
            if string[n] == char:
                pos.append(n)
        return pos
    
    s = "sentence"
    print(charposition(s, 'e')) 
    
    #Output: [1, 4, 7]
    
  • 15

    more_itertools.locate是第三方工具,可查找满足条件的所有项目的指示 .

    在这里,我们找到了字母 "i" 的所有索引位置 .

    import more_itertools as mit
    
    
    s = "supercalifragilisticexpialidocious"
    list(mit.locate(s, lambda x: x == "i"))
    # [8, 13, 15, 18, 23, 26, 30]
    
  • 12
    >>> s="mystring"
    >>> s.index("r")
    4
    >>> s.find("r")
    4
    

    “啰嗦”的方式

    >>> for i,c in enumerate(s):
    ...   if "r"==c: print i
    ...
    4
    

    得到子串,

    >>> s="mystring"
    >>> s[4:10]
    'ring'
    
  • 1

    当字符串包含重复字符时会发生什么?根据我对 index() 的经验,我看到重复你得到相同的索引 .

    例如:

    s = 'abccde'
    for c in s:
        print('%s, %d' % (c, s.index(c)))
    

    会回来:

    a, 0
    b, 1
    c, 2
    c, 2
    d, 4
    

    在这种情况下,你可以这样做:

    for i, character in enumerate(my_string):
       # i is the position of the character in the string
    

相关问题