使用Python迭代字符串中的每个字符 [英] Iterating each character in a string using Python

查看:252
本文介绍了使用Python迭代字符串中的每个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  std :: string str =Hello World!; 

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

如何在Python中迭代字符串?

解决方案

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

  for c在字符串中:
#do与c
的东西

你可以迭代几乎任何东西python使用 for循环构造,



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

 开放(文件名)为f:
换行f:
#用行
做某事

如果这看起来很神奇,那就好了,但背后的想法非常简单。



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



只需实现一个定义 next()方法的迭代器,并实现 __iter __ 类上的方法使其可迭代。 ( __ iter __ 当然应该返回一个迭代器对象,即一个定义 next()的对象<) / p>

查看官方文档


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?

解决方案

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

这篇关于使用Python迭代字符串中的每个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆