使用 Python 迭代字符串中的每个字符
如何在 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)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
正如 Johannes 指出的,
您可以使用
for 循环
构造来迭代 python 中的几乎所有内容,例如,
open("file.txt")
返回一个文件对象(并且打开文件),迭代它迭代该文件中的行如果这看起来像魔术,那么它有点像,但其背后的想法非常简单。
有一个简单的迭代器协议,可以应用于任何类型的对象,以使
for
循环对其起作用。只需实现一个定义
next()
方法的迭代器,并在类上实现一个__iter__
方法即可使其可迭代。 (__iter__
当然应该返回一个迭代器对象,即定义next()
的对象) org/library/stdtypes.html#iterator-types" rel="noreferrer">查看官方文档
As Johannes pointed out,
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 fileIf 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 definesnext()
)See official documentation
如果您需要在遍历字符串时访问索引,请使用
enumerate()
:
If you need access to the index as you iterate through the string, use
enumerate()
:更简单:
Even easier:
为了给出一个更全面的答案,如果你真的想将方钉强行插入圆孔中,那么迭代字符串的 C 方法可以应用于 Python。
但话又说回来,当字符串本质上是可迭代的时,为什么要这样做呢?
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.
But then again, why do that when strings are inherently iterable?
好吧,你也可以做一些像这样有趣的事情,并通过使用 for 循环来完成你的工作
答案是
M r 。 S uryaa
但是,由于 range() 创建了一个序列值列表,因此您可以直接使用名称,
这也会产生相同的结果,而且看起来更好,并且适用于任何序列,如列表、元组和字典。
我们使用了两个内置函数(Python 社区中的 BIF)
1) range() - range() BIF 用于创建索引
示例
2) len() - len() BIF 用于找出给定字符串的长度
Well you can also do something interesting like this and do your job by using for loop
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
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
2) len() - len() BIF is used to find out the length of given string
如果您想使用一种更实用的方法来迭代字符串(也许以某种方式对其进行转换),您可以将字符串拆分为字符,对每个字符应用一个函数,然后将生成的字符列表重新连接回字符串。
字符串本质上是字符列表,因此“map”将迭代字符串 - 作为第二个参数 - 将函数 - 第一个参数 - 应用于每个字符。
例如,这里我使用简单的 lambda 方法,因为我想做的只是对字符进行简单的修改:这里,增加每个字符值:
或者更一般地说:
其中 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:
or more generally:
where my_function takes a char value and returns a char value.
这里的几个答案使用
范围
。xrange
通常更好,因为它返回一个生成器,而不是一个完全实例化的列表。 当内存和/或长度变化很大的可迭代对象可能成为问题时,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.您还可以执行以下操作:
这不使用循环,但内部 print 语句会处理它。
*
将字符串解包到列表中并将其发送到 print 语句sep='\n'
将确保下一个字符打印在新行上输出将是:
如果您确实需要循环语句,那么正如其他人提到的,您可以使用 for 循环,如下所示:
You can also do the following:
This does not use loops but internally print statement takes care of it.
*
unpacks the string into a list and sends it to the print statementsep='\n'
will ensure that the next char is printed on a new lineThe output will be:
If you do need a loop statement, then as others have mentioned, you can use a for loop like this:
如果您曾经遇到过需要使用 __next__() 获取单词的下一个字符的情况,请记住创建一个 string_iterator 并迭代它而不是 < code>原始字符串(它没有 __next__() 方法)
在此示例中,当我找到 char =
[
时,我会继续查找下一个单词虽然我找不到]
,所以我需要在这里使用 __next__ 对字符串进行 for 循环没有帮助
If you ever run in a situation where you need to
get the next char of the word using __next__()
, remember to create astring_iterator
and iterate over it and not theoriginal 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