【发布时间】:2011-01-18 15:58:42
【问题描述】:
如何在 Python 中获取字符在字符串中的位置?
【问题讨论】:
如何在 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。 start 和 end 的默认值以及负值的解释与切片相同。
还有:
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]
【讨论】:
print( [pos for pos, char in enumerate(s) if char == c])
foo = ( [pos for pos, char in enumerate(s) if char == c]) 会将坐标 foo 放在列表格式中。我觉得这真的很有帮助
>>> 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'
【讨论】:
str[from:to] 其中from 和to 是索引
为了完成,如果我想在文件名中找到扩展名以便检查它,我需要找到最后一个'.',在这种情况下使用 rfind:
path = 'toto.titi.tata..xls'
path.find('.')
4
path.rfind('.')
15
在我的情况下,我使用以下内容,无论完整的文件名是什么:
filename_without_extension = complete_name[:complete_name.rfind('.')]
【讨论】:
left = q.find("{"); right = q.rfind("}")。
当字符串包含重复字符时会发生什么?
根据我对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
【讨论】:
enumerate 更适合这种事情。
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]
【讨论】:
Python 有一个内置的字符串方法可以完成这项工作:index()。
string.index(value, start, end)
地点:
def character_index():
string = "Hello World! This is an example sentence with no meaning."
match = "i"
return string.index(match)
print(character_index())
> 15
假设您需要字符 match 所在的所有索引,而不仅仅是第一个索引。
pythonic 方式是使用enumerate()。
def character_indexes():
string = "Hello World! This is an example sentence with no meaning."
match = "i"
indexes_of_match = []
for index, character in enumerate(string):
if character == match:
indexes_of_match.append(index)
return indexes_of_match
print(character_indexes())
# [15, 18, 42, 53]
或者更好的列表理解:
def character_indexes_comprehension():
string = "Hello World! This is an example sentence with no meaning."
match = "i"
return [index for index, character in enumerate(string) if character == match]
print(character_indexes_comprehension())
# [15, 18, 42, 53]
【讨论】:
more_itertools.locate 是一个第三方工具,用于查找满足条件的项目的所有指标。
在这里我们找到了字母"i"的所有索引位置。
给定
import more_itertools as mit
text = "supercalifragilisticexpialidocious"
search = lambda x: x == "i"
代码
list(mit.locate(text, search))
# [8, 13, 15, 18, 23, 26, 30]
【讨论】:
使用 numpy 快速访问所有索引的解决方案:
string_array = np.array(list(my_string))
char_indexes = np.where(string_array == 'C')
【讨论】:
我发现的大多数方法都是指在字符串中查找第一个子字符串。要查找所有子字符串,您需要解决。
例如:
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]
【讨论】: