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

发布于 2024-07-13 08:28:24 字数 61 浏览 6 评论 0原文

如何在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

兰花执着 2024-07-20 08:28:24

正如 Johannes 指出的,

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

您可以使用 for 循环 构造来迭代 python 中的几乎所有内容,

例如,open("file.txt") 返回一个文件对象(并且打开文件),迭代它迭代该文件中的行

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

如果这看起来像魔术,那么它有点像,但其背后的想法非常简单。

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

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

) org/library/stdtypes.html#iterator-types" rel="noreferrer">查看官方文档

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

时光与爱终年不遇 2024-07-20 08:28:24

如果您需要在遍历字符串时访问索引,请使用 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
-小熊_ 2024-07-20 08:28:24

更简单:

for c in "test":
    print c

Even easier:

for c in "test":
    print c
宣告ˉ结束 2024-07-20 08:28:24

为了给出一个更全面的答案,如果你真的想将方钉强行插入圆孔中,那么迭代字符串的 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
微暖i 2024-07-20 08:28:24

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

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

答案是

M r 。 S uryaa

但是,由于 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

城歌 2024-07-20 08:28:24

如果您想使用一种更实用的方法来迭代字符串(也许以某种方式对其进行转换),您可以将字符串拆分为字符,对每个字符应用一个函数,然后将生成的字符列表重新连接回字符串。

字符串本质上是字符列表,因此“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.

美煞众生 2024-07-20 08:28:24

这里的几个答案使用范围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.

二货你真萌 2024-07-20 08:28:24

您还可以执行以下操作:

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

这不使用循环,但内部 print 语句会处理它。

* 将字符串解包到列表中并将其发送到 print 语句

sep='\n' 将确保下一个字符打印在新行上

输出将是:

H
e
l
l
o
 
W
o
r
l
d
!

如果您确实需要循环语句,那么正如其他人提到的,您可以使用 for 循环,如下所示:

for x in txt: print (x)

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.

* unpacks the string into a list and sends it to the print statement

sep='\n' will ensure that the next char is printed on a new line

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 x in txt: print (x)
凉薄对峙 2024-07-20 08:28:24

如果您曾经遇到过需要使用 __next__() 获取单词的下一个字符的情况,请记住创建一个 string_iterator 并迭代它而不是 < code>原始字符串(它没有 __next__() 方法)

在此示例中,当我找到 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文