使用Python迭代字符串中的每个字符

问题:使用Python迭代字符串中的每个字符

在C ++中,我可以std::string像这样迭代:

std::string str = "Hello World!";

for (int i = 0; i < str.length(); ++i)
{
    std::cout << str[i] << std::endl;
}

如何在Python中遍历字符串?

In C++, I can iterate over an std::string like this:

std::string str = "Hello World!";

for (int i = 0; i < str.length(); ++i)
{
    std::cout << str[i] << std::endl;
}

How do I iterate over a string in Python?


回答 0

正如约翰内斯指出的那样,

for c in "string":
    #do something with c

您可以使用struct迭代python中的几乎所有内容for loop

例如,open("file.txt")返回文件对象(并打开文件),对其进行迭代,然后对该文件中的行进行迭代

with open(filename) as f:
    for line in f:
        # do something with line

如果那看起来像魔术,那还算不错,但是它背后的想法真的很简单。

有一个简单的迭代器协议可以应用于任何对象,以使for循环在其上起作用。

只需实现定义一个next()方法的迭代器,然后__iter__在类上实现一个方法使其可迭代即可。(__iter__当然,应返回一个迭代器对象,即定义的对象next()

参阅官方文件

As Johannes pointed out,

for c in "string":
    #do something with c

You can iterate pretty much anything in python using the for loop construct,

for example, open("file.txt") returns a file object (and opens the file), iterating over it iterates over lines in that file

with open(filename) as f:
    for line in f:
        # do something with line

If that seems like magic, well it kinda is, but the idea behind it is really simple.

There’s a simple iterator protocol that can be applied to any kind of object to make the for loop work on it.

Simply implement an iterator that defines a next() method, and implement an __iter__ method on a class to make it iterable. (the __iter__ of course, should return an iterator object, that is, an object that defines next())

See official documentation


回答 1

如果在遍历字符串时需要访问索引,请使用enumerate()

>>> for i, c in enumerate('test'):
...     print i, c
... 
0 t
1 e
2 s
3 t

If you need access to the index as you iterate through the string, use enumerate():

>>> for i, c in enumerate('test'):
...     print i, c
... 
0 t
1 e
2 s
3 t

回答 2

更简单:

for c in "test":
    print c

Even easier:

for c in "test":
    print c

回答 3

只是为了做出更全面的回答,如果您确实想将方钉强行塞入圆孔中,则对字符串进行迭代的C方法可以在Python中应用。

i = 0
while i < len(str):
    print str[i]
    i += 1

但是话又说回来,当字符串具有固有的可迭代性时,为什么要这样做呢?

for i in str:
    print i

Just to make a more comprehensive answer, the C way of iterating over a string can apply in Python, if you really wanna force a square peg into a round hole.

i = 0
while i < len(str):
    print str[i]
    i += 1

But then again, why do that when strings are inherently iterable?

for i in str:
    print i

回答 4

好吧,您也可以像这样做一些有趣的事情,并通过使用for循环来完成您的工作

#suppose you have variable name
name = "Mr.Suryaa"
for index in range ( len ( name ) ):
    print ( name[index] ) #just like c and c++ 

答案是

先生 。苏里亚

但是,由于range()创建的是序列值的列表,因此您可以直接使用名称

for e in name:
    print(e)

这也可以产生相同的结果,并且看起来更好,并且可以与列表,元组和字典之类的任何序列一起使用。

我们曾经使用过“内置函数”(Python社区中的BIF)

1)range()-range()BIF用于创建索引示例

for i in range ( 5 ) :
can produce 0 , 1 , 2 , 3 , 4

2)len()-len()BIF用于找出给定字符串的长度

Well you can also do something interesting like this and do your job by using for loop

#suppose you have variable name
name = "Mr.Suryaa"
for index in range ( len ( name ) ):
    print ( name[index] ) #just like c and c++ 

Answer is

M r . S u r y a a

However since range() create a list of the values which is sequence thus you can directly use the name

for e in name:
    print(e)

This also produces the same result and also looks better and works with any sequence like list, tuple, and dictionary.

We have used tow Built in Functions ( BIFs in Python Community )

1) range() – range() BIF is used to create indexes Example

for i in range ( 5 ) :
can produce 0 , 1 , 2 , 3 , 4

2) len() – len() BIF is used to find out the length of given string


回答 5

如果您想使用一种更实用的方法遍历字符串(可能以某种方式进行转换),则可以将字符串拆分为字符,对每个函数应用一个函数,然后将所得的字符列表重新组合为字符串。

字符串本质上是一个字符列表,因此“ map”将遍历字符串-作为第二个参数-将函数-第一个参数应用于每个参数。

例如,这里我使用一种简单的lambda方法,因为我要做的只是对字符的微不足道的修改:在这里,增加每个字符的值:

>>> ''.join(map(lambda x: chr(ord(x)+1), "HAL"))
'IBM'

或更一般而言:

>>> ''.join(map(my_function, my_string))

其中my_function接受一个char值并返回一个char值。

If you would like to use a more functional approach to iterating over a string (perhaps to transform it somehow), you can split the string into characters, apply a function to each one, then join the resulting list of characters back into a string.

A string is inherently a list of characters, hence ‘map’ will iterate over the string – as second argument – applying the function – the first argument – to each one.

For example, here I use a simple lambda approach since all I want to do is a trivial modification to the character: here, to increment each character value:

>>> ''.join(map(lambda x: chr(ord(x)+1), "HAL"))
'IBM'

or more generally:

>>> ''.join(map(my_function, my_string))

where my_function takes a char value and returns a char value.


回答 6

这里使用几个答案rangexrange通常会更好,因为它返回生成器,而不是完全实例化的列表。在内存和/或长度可变的可迭代项可能成为问题的情况下,它xrange是优越的。

Several answers here use range. xrange is generally better as it returns a generator, rather than a fully-instantiated list. Where memory and or iterables of widely-varying lengths can be an issue, xrange is superior.


回答 7

如果您曾经在需要的情况下运行get the next char of the word using __next__(),请记住创建一个string_iterator并对其进行迭代,而不要迭代original string (it does not have the __next__() method)

在此示例中,当我找到一个char =时,[我一直在寻找下一个单词,但没有找到],所以我需要使用__next__

这里的字符串的for循环将无济于事

myString = "'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"
processedInput = ""
word_iterator = myString.__iter__()
for idx, char in enumerate(word_iterator):
    if char == "'":
        continue

    processedInput+=char

    if char == '[':
        next_char=word_iterator.__next__()
        while(next_char != "]"):
          processedInput+=next_char
          next_char=word_iterator.__next__()
        else:
          processedInput+=next_char

If you ever run in a situation where you need to get the next char of the word using __next__(), remember to create a string_iterator and iterate over it and not the original string (it does not have the __next__() method)

In this example, when I find a char = [ I keep looking into the next word while I don’t find ], so I need to use __next__

here a for loop over the string wouldn’t help

myString = "'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"
processedInput = ""
word_iterator = myString.__iter__()
for idx, char in enumerate(word_iterator):
    if char == "'":
        continue

    processedInput+=char

    if char == '[':
        next_char=word_iterator.__next__()
        while(next_char != "]"):
          processedInput+=next_char
          next_char=word_iterator.__next__()
        else:
          processedInput+=next_char