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


当前回答

string.find(character)  
string.index(character)  

也许您想查看一下文档,以找出两者之间的区别。

其他回答

>>> s="mystring"
>>> s.index("r")
4
>>> s.find("r")
4

“冗长”的方式

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

要得到substring,

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

一个字符可能在字符串中出现多次。例如,在一个字符串句子中,e的位置是1,4,7(因为索引通常从0开始)。但我发现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]

使用numpy快速访问所有索引的解决方案:

string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')

有两个字符串方法,find()和index()。两者之间的区别在于当没有找到搜索字符串时会发生什么。find()返回-1,index()引发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手册

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

And:

字符串。索引(s, sub[, start[, end]]) 类似于find(),但在未找到子字符串时引发ValueError。

我发现的大多数方法都是指查找字符串中的第一个子字符串。要找到所有的子字符串,您需要处理。

例如:

定义字符串

vars = 'iloveyoutosimidaandilikeyou'

定义子字符串

key = 'you'

定义一个函数,该函数可以找到字符串中所有子字符串的位置

def find_all_loc(vars, key):

    pos = []
    start = 0
    end = len(vars)

    while True: 
        loc = vars.find(key, start, end)
        if  loc is -1:
            break
        else:
            pos.append(loc)
            start = loc + len(key)
            
    return pos

pos = find_all_loc(vars, key)

print(pos)
[5, 24]