How to get the position of a character in Python?
在Python中,如何获取字符串中字符的位置?
它有两种字符串方法:
1 2 3 4 5 | >>> myString = 'Position of a character' >>> myString.find('s') 2 >>> myString.find('x') -1 |
使用
1 2 3 4 5 6 7 | >>> 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]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained ins[start:end] . Return-1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.
还有:
string.index(s, sub[, start[, end]])
Likefind() but raiseValueError when the substring is not found.
为了完整起见,如果需要查找字符串中字符的所有位置,可以执行以下操作:
1 2 3 | s = 'shak#spea#e' c = '#' print [pos for pos, char in enumerate(s) if char == c] |
返回
1 2 3 4 5 | >>> s="mystring" >>> s.index("r") 4 >>> s.find("r") 4 |
"长卷"方式
1 2 3 4 | >>> for i,c in enumerate(s): ... if"r"==c: print i ... 4 |
要获取子字符串,
1 2 3 | >>> s="mystring" >>> s[4:10] 'ring' |
当字符串包含重复字符时会发生什么?根据我对
例如:
1 2 3 | s = 'abccde' for c in s: print('%s, %d' % (c, s.index(c))) |
将返回:
1 2 3 4 5 | a, 0 b, 1 c, 2 c, 2 d, 4 |
在这种情况下,您可以这样做:
1 2 | for i, character in enumerate(my_string): # i is the position of the character in the string |
为了完成,如果我想在文件名中查找扩展名以进行检查,我需要查找最后一个".",在这种情况下,使用rfind:
1 2 3 4 5 | path = 'toto.titi.tata..xls' path.find('.') 4 path.rfind('.') 15 |
在我的例子中,我使用了以下方法,无论完整的文件名是什么:
1 | filename_without_extension = complete_name[:complete_name.rfind('.')] |
1 2 | string.find(character) string.index(character) |
也许您想看看文档,了解两者之间的区别。
一个字符可能在一个字符串中出现多次。例如,在字符串
1 2 3 4 5 6 7 8 9 10 11 | 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] |
在这里我们找到了字母
1 2 3 4 5 6 | import more_itertools as mit s ="supercalifragilisticexpialidocious" list(mit.locate(s, lambda x: x =="i")) # [8, 13, 15, 18, 23, 26, 30] |