Iterating each character in a string using Python

2019-01-03 11:31发布

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?

8条回答
太酷不给撩
2楼-- · 2019-01-03 12:06

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
查看更多
劳资没心,怎么记你
3楼-- · 2019-01-03 12:07

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
查看更多
啃猪蹄的小仙女
4楼-- · 2019-01-03 12:09

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.

查看更多
Luminary・发光体
5楼-- · 2019-01-03 12:12

You can use formatted string literals (PEP498; Pyton 3.6+) with print and sequence unpacking and 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:

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

(0, 'H')
(1, 'e')
(2, 'l')
(3, 'l')
(4, 'o')
(5, '!')
查看更多
乱世女痞
6楼-- · 2019-01-03 12:20

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

查看更多
男人必须洒脱
7楼-- · 2019-01-03 12:20

Even easier:

for c in "test":
    print c
查看更多
登录 后发表回答