具有重复字符python的字符串数组

时间:2016-11-17 20:01:07

标签: python

我试图打破一个句子,例如:"这个男孩很好",然后在每个字母的句子中得到这个位置,但每次我去写信& #39; o',这两个字母的位置保持不变。我该如何分开这两个相同的字母?

with open("d:\Users\hazembazem\Desktop\python random\crap\encrypt.txt", "rb") as f:
    file= f.read()
    print file
    file= list(file)
    for item in file:
        a=file.index(item)
    print (a)

该文件只是一个txt文件,其中包含:"这个男孩很好"。

a意味着是角色的所在地,但它反过来告诉我这个:

0
1
2
3
4
5
6
3
8
9
10
3
12
5
5
15

4 个答案:

答案 0 :(得分:2)

  

string.index(s, sub[, start[, end]])

     

find()类似,但在找不到子字符串时会引发ValueError

  

string.find(s, sub[, start[, end]])

     

返回s中找到子字符串sub的最低索引...

所以,是的,那不是你想要的。

检查出来

with open("filename") as f:
    string = f.read()
    print range(len(string))
    for i,c in enumerate(string):
        print i,c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
0 t
1 h
2 e
3  
4 b
5 o
6 y
7  
8 w
9 a
10 s
11  
12 g
13 o
14 o
15 d

答案 1 :(得分:0)

str.index/str.find仅返回最左侧的索引。找到每个字母后,您需要传递要开始搜索字母的索引。像这样:

>>> found = -1
>>> for i in xrange(x.count('o')):
>>>     found = x.index('o', found+1)
>>>     print 'Found "o" at index: {}'.format(found)

Found "o" at index: 5
Found "o" at index: 13
Found "o" at index: 14

答案 2 :(得分:0)

如果使用索引for循环遍历文本,则只需使用索引打印字符及其位置

text = list(file)
for index in range(0,len(text)):
    print(a[index], index)

答案 3 :(得分:0)

如果您希望在字符及其相应索引之间进行映射并以dict的形式存储,则可以将collections.defaultdict()enumerate()一起用作:

from collections import defaultdict 

my_string = "the boy was good"
char_mapping = defaultdict(list)

for i, c in enumerate(my_string):
    char_mapping[c].append(i)

# Content of `char_mapping`:
# {'a': [9], 
#  ' ': [3, 7, 11], 
#  'b': [4], 
#  'e': [2], 
#  'd': [15], 
#  'g': [12],
#  'h': [1],
#  'o': [5, 13, 14],
#  's': [10],
#  't': [0],
#  'w': [8],
#  'y': [6]})