4 ways to traverse Python strings

There are 4 ways to traverse python strings:

1. Subscript method

2. for in

3. Iter built-in functions

4. enumerate

Among them, the subscript method and enumerate are suitable for scenarios where subsequent characters need to be judged, such as looping to the subscript index and requiring judgment of index+1 characters. The most typical problem is the parser, the algorithm for judging "(())" paired parentheses.

"for in" and iter are suitable for a class of topics that directly deal with characters, such as size conversion and string comparison.

In short, if you need to use subscripts, use subscript and enumerate, where enumerate has better performance than subscript.

(Note: This article is based on Python3.x)

The first way, for in

girl_str = "love You"
 
for every_char in girl_str:
 print(every_char)

The second way, built-in function range() or xrange(), just pass in the length of the string

girl_str = "love You"
 
for index in range(len(girl_str)):
 print(girl_str[index])

The third way, the built-in function enumerate()

girl_str = "love You"
 
for index, every_char in enumerate(girl_str):
 print(str(index) + every_char)
 

The fourth way, the built-in function iter()

girl_str = "love You"
 
for every_char in iter(girl_str):
 print(every_char)

So far, this article on the 4 ways of traversing Python strings is introduced. More exciting can be added to the exchange of "606115027"

Guess you like

Origin blog.csdn.net/weixin_45293202/article/details/111598267