Skip to main content
 首页 » 编程设计

Python2.7之遍历字符串索引并仅打印偶数或奇数索引值时输出不正确

2025年05月04日20jillzhang

当遍历一个字符串并只打印偶数字符串索引的值时,Python 正在打印 string.index(3) 处的值,即使我要求它仅在索引为偶数时打印该值。我想知道为什么会这样。这是我一直在使用的代码:

    my_string = 'Hello, World!' 
    for i in my_string: 
        if my_string.index(i) % 2 == 0: 
            print i 
        else: 
            print my_string.index(i) 

当我们运行代码时,它应该返回:

H 
1 
l 
3 
o 
5 
 
7 
o 
9 
l 
11 
! 

但是,Python 正在返回:

H 
1 
l 
l  
o 
5 
 
7 
o 
9 
l 
11 
! 

如您所见,返回索引 [3] 处的“l”而不是 3。

这似乎是我使用的每个解释器的情况,所以我假设这是 Python 的问题。有什么办法可以解决这个问题吗?它发生在其他人身上吗?如果有人正在编写需要准确分离偶数和奇数索引的程序,这似乎是一个非常大的问题。

请您参考如下方法:

.index 并不像您想象的那样 - 它返回 first 索引。在你的情况下你有:

 Hello... # text 
 01234    # indices 

l 的第一个索引是2。这是偶数,而不是显示。您想要使用的是 enumerate:

my_string = 'Hello, World!' 
for i, char in enumerate(my_string): 
    if i % 2 == 0: 
        print char 
    else: 
        print i 

如果你read the docs你会看到:

s.index(x) | index of the first occurrence of x in s

你也可以这样试试:

Python 2.7.10 (default, Oct 23 2015, 19:19:21)  
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0. 
Type "help", "copyright", "credits" or "license" for 
>>> help('hello'.index) 
Help on built-in function index: 
 
index(...) 
    S.index(sub [,start [,end]]) -> int 
 
    Like S.find() but raise ValueError when the substring is not found. 

(这应该引导你

>>> help('hello'.find) 
Help on built-in function find: 
 
find(...) 
    S.find(sub [,start [,end]]) -> int 
 
    Return the lowest index in S where substring sub is found, 
    such that sub is contained within S[start:end].  Optional 
    arguments start and end are interpreted as in slice notation. 
 
    Return -1 on failure. 

lowest index in S

在 'Hello, World!' 中,l 的最低 索引是 2。o 的最低索引> 是 4。如果您获取代码并将逻辑翻转为 if i % 2:,那么您将看到第二个 o< 得到 4/!