Four Ways of Traversing Strings of Python

  • 2021-08-21 20:52:19
  • OfStack

There are four ways for python to traverse strings:

1. Subscript method

2. for in

3. iter built-in functions

4. enumerate

Among them, subscript method and enumerate are suitable for scenes where subsequent characters need to be judged, such as circulating to subscript index and requiring to judge characters of index+1. The most typical problem is the parser, the algorithm for judging "(())", which is a pair of parentheses.

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

In a word, if subscript is needed, subscript method and enumerate are used, and enumerate has better performance than subscript method.

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

Mode 1, for in


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

In the second way, the built-in function range () or xrange () just passes in the string length


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

In 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)
 

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


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

Related articles: