Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating each character in a string using 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?

like image 261
Paradius Avatar asked Feb 11 '09 19:02

Paradius


People also ask

Can we iterate over string in Python?

In Python, while operating with String, one can do multiple operations on it. Let's see how to iterate over characters of a string in Python. Example #4: Iteration over particular set of element.

How do you iterate through an alphabet in Python?

In addition to string. ascii_lowercase you should also take a look at the ord and chr built-ins. ord('a') will give you the ascii value for 'a' and chr(ord('a')) will give you back the string 'a' . Using these you can increment and decrement through character codes and convert back and forth easily enough.

How do you access all the characters in a string in Python?

Individual characters in a string can be accessed by specifying the string name followed by a number in square brackets ( [] ). String indexing in Python is zero-based: the first character in the string has index 0 , the next has index 1 , and so on.


1 Answers

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

like image 73
hasen Avatar answered Nov 27 '22 14:11

hasen