问题:如何获得字符在Python中的位置?

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

How can I get the position of a character inside a string in python?


回答 0

这有两个String的方法,find()index()。两者之间的区别在于找不到搜索字符串时会发生什么。 find()回报-1index()加薪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

Python手册

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

和:

string.index(s, sub[, start[, end]])
喜欢,find()但是ValueError在找不到子字符串时提高。

There are two string methods for this, find() and index(). The difference between the two is what happens when the search string isn’t found. find() returns -1 and index() raises ValueError.

Using find()

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

Using 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

From the Python manual

string.find(s, sub[, start[, end]])
Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

And:

string.index(s, sub[, start[, end]])
Like find() but raise ValueError when the substring is not found.


回答 1

仅出于完整性考虑,如果需要查找字符串中字符的所有位置,可以执行以下操作:

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

它将返回 [4, 9]

Just for a sake of completeness, if you need to find all positions of a character in a string, you can do the following:

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

which will return [4, 9]


回答 2

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

“长ed”方式

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

得到子串,

>>> s="mystring"
>>> s[4:10]
'ring'
>>> s="mystring"
>>> s.index("r")
4
>>> s.find("r")
4

“Long winded” way

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

to get substring,

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

回答 3

只是为了完成,如果要在文件名中找到扩展名以进行检查,则需要找到最后一个“。”,在这种情况下,请使用rfind:

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

就我而言,我使用以下命令,无论完整的文件名是什么,它都可以工作:

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

Just for completion, in the case I want to find the extension in a file name in order to check it, I need to find the last ‘.’, in this case use rfind:

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

in my case, I use the following, which works whatever the complete file name is:

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

回答 4

当字符串包含重复字符时会发生什么?从我的经验中,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

What happens when the string contains a duplicate character? from my experience with index() I saw that for duplicate you get back the same index.

For example:

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

would return:

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

In that case you can do something like that:

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

回答 5

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

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

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

Perhaps you’d like to have a look at the documentation to find out what the difference between the two is.


回答 6

一个字符可能在字符串中多次出现。例如,在字符串中sentence,位置eis是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]

A character might appear multiple times in a string. For example in a string sentence, position of e is 1, 4, 7 (because indexing usually starts from zero). but what I find is both of the functions find() and index() returns first position of a character. So, this can be solved doing this:

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]

回答 7

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]

more_itertools.locate is a third-party tool that finds all indicies of items that satisfy a condition.

Here we find all index locations of the letter "i".

import more_itertools as mit


s = "supercalifragilisticexpialidocious"
list(mit.locate(s, lambda x: x == "i"))
# [8, 13, 15, 18, 23, 26, 30]

回答 8

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

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

A solution with numpy for quick access to all indexes:

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。