简体   繁体   English

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

[英]Iterating each character in a string using Python

How can I iterate over a string in Python (get each character from the string, one at a time, each time through a loop)?我如何在 Python 中迭代一个字符串(从字符串中获取每个字符,一次一个,每次通过一个循环)?

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 loop构造在 python 中迭代几乎所有内容,

for example, open("file.txt") returns a file object (and opens the file), iterating over it iterates over lines in that file例如, open("file.txt")返回一个文件对象(并打开文件),遍历它遍历该文件中的行

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.有一个简单的迭代器协议,可以应用于任何类型的对象,使for循环在其上运行。

Simply implement an iterator that defines a next() method, and implement an __iter__ method on a class to make it iterable.只需实现一个定义next()方法的迭代器,并在类上实现__iter__方法,使其可迭代。 (the __iter__ of course, should return an iterator object, that is, an object that defines next() ) (当然, __iter__应该返回一个迭代器对象,即定义next()的对象)

See official documentation 看官方文档

If you need access to the index as you iterate through the string, use enumerate() :如果在遍历字符串时需要访问索引,请使用enumerate()

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

Even easier:更简单:

for c in "test":
    print c

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.只是为了给出更全面的答案,如果您真的想将方形钉子强行插入圆孔,则迭代字符串的 C 方法可以应用于 Python。

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

Well you can also do something interesting like this and do your job by using for loop那么你也可以做一些像这样有趣的事情并通过使用 for 循环来完成你的工作

#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 uryaa苏里亚

However since range() create a list of the values which is sequence thus you can directly use the name但是,由于 range() 创建了一个序列值列表,因此您可以直接使用名称

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 )我们使用了两个内置函数(Python 社区中的 BIF)

1) range() - range() BIF is used to create indexes Example 1) range() - range() BIF用于创建索引的例子

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 2) len() - len() BIF 用于找出给定字符串的长度

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.字符串本质上是一个字符列表,因此 'map' 将遍历字符串 - 作为第二个参数 - 将函数 - 第一个参数 - 应用于每个字符串。

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:例如,在这里我使用了一个简单的 lambda 方法,因为我想做的只是对字符进行微不足道的修改:在这里,增加每个字符值:

>>> ''.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.其中 my_function 接受一个 char 值并返回一个 char 值。

Several answers here use range .这里的几个答案使用range xrange is generally better as it returns a generator, rather than a fully-instantiated list. xrange通常更好,因为它返回一个生成器,而不是一个完全实例化的列表。 Where memory and or iterables of widely-varying lengths can be an issue, xrange is superior.在内存和/或长度变化很大的可迭代对象可能成为问题的地方, xrange更胜一筹。

You can use formatted string literals ( PEP498 ; Pyton 3.6+) with print and sequence unpacking and enumerate : 您可以使用带有print和序列解包的格式化字符串文字( PEP498 ; Pyton 3.6+)并enumerate

print(*(f'{idx} {char}' for idx, char in enumerate('Hello!')), sep='\n')

0 H
1 e
2 l
3 l
4 o
5 !

If printing tuple values are sufficient, there is no need for the generator expression: 如果打印tuple值足够,则不需要生成器表达式:

print(*enumerate('Hello!'), sep='\n')

(0, 'H')
(1, 'e')
(2, 'l')
(3, 'l')
(4, 'o')
(5, '!')

You can also do the following:您还可以执行以下操作:

txt = "Hello World!"
print (*txt, sep='\n')

This does not use loops but internally print statement takes care of it.这不使用循环,但内部 print 语句会处理它。

* unpacks the string into a list and sends it to the print statement *将字符串解包到一个列表中并将其发送到 print 语句

sep='\n' will ensure that the next char is printed on a new line sep='\n'将确保下一个字符打印在新行上

The output will be:输出将是:

H
e
l
l
o
 
W
o
r
l
d
!

If you do need a loop statement, then as others have mentioned, you can use a for loop like this:如果您确实需要循环语句,那么正如其他人提到的那样,您可以像这样使用 for 循环:

for x in txt: print (x)

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)如果您在需要get the next char of the word using __next__()情况下运行,请记住创建一个string_iterator并迭代它而不是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__在这个例子中,当我找到一个 char = [ I keep looking into the next word while I don't find ] ,所以我需要使用 __next__

here a for loop over the string wouldn't help这里的字符串上的 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM