如何在python中获取字符串中字符的位置?
有两种字符串方法,find()
和index()
。两者之间的区别是找不到搜索字符串时发生的情况。 find()
返回-1
和index()
引发ValueError
。
find()
>>> myString = 'Position of a character'
>>> myString.find('s')
2
>>> myString.find('x')
-1
index()
>>> 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
string.find(s, sub[, start[, end]])
返回s中找到子字符串sub的最低索引,使得sub完全包含在s[start:end]
中。失败时返回-1
。开始和结束的默认值以及负值的解释与切片的默认值相同。
和:
string.index(s, sub[, start[, end]])
像find()
一样,但是当找不到子串时会提升ValueError
。
只是为了完整起见,如果您需要查找字符串中字符的所有位置,您可以执行以下操作:
s = 'shak#spea#e'
c = '#'
print [pos for pos, char in enumerate(s) if char == c]
这将返回[4, 9]
>>> 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'
当字符串包含重复字符时会发生什么?根据我对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
只是为了完成,如果我想在文件名中找到扩展名来检查它,我需要找到最后的'。',在这种情况下使用rfind:
path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15
在我的情况下,我使用以下,无论完整的文件名是什么,它都适用:
filename_without_extension = complete_name[:complete_name.rfind('.')]
string.find(character)
string.index(character)
也许你想看看the documentation,看看两者之间的区别是什么。
字符可能会在字符串中多次出现。例如,在字符串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]