Python中的字符串数组与重复字符

2024-06-28 20:01:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着把一个句子分成几个字符,比如:“男孩很好”,然后在每个字母的句子中找到位置,但是每次我找到字母“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

Tags: 文件txtwith字母randomopenitem字符
3条回答

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

Like find() but raise ValueError when the substring is not found.


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

Return the lowest index in s where the substring sub is found...


所以,是的,那不是你想要的。你知道吗

看看这个

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

如果使用索引for循环在文本上循环,则可以简单地使用索引打印字符及其位置

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

^{}/^{}只返回最左边的索引。在找到每个字母后,您需要传递开始搜索该字母的位置的索引。像这样:

>>> 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

相关问题 更多 >