Python iterating over string

Python : How to iterate over the characters in string ?

In this article we will discuss different ways to iterate or loop over all the characters of string in forward, backward direction and also by skipping over certain characters.

Iterate over string using for loop

Iterating over the string is simple using for loop and in operator i.e.

sampleStr = "Hello!!" print("**** Iterate over string using for loop****") for elem in sampleStr: print(elem)
**** Iterate over string using for loop**** H e l l o ! !

Iterate over string with index using range()

range(len (stringObj) ) function will generate the sequence from 0 to n -1 ( n is size of string) . Now iterate over this sequence and for each index access the character from string using operator [] i.e.

Читайте также:  Java set client property

Frequently Asked:

print("**** Iterate over string with index using range() ****") for i in range( len(sampleStr) ): print(sampleStr[i])

It will print the string contents

**** Iterate over string with index using range() **** H e l l o ! !

Iterate over a portion of string only

To iterate over a portion of string like a sub string , we can use slicing operator to generate a sub string and then iterate over that sub string. To generate a slice we will use [] operator i.e.

string[start : stop : step size]

We can pass the start and stop index to generate a sub string and then we can iterate over it. For example, lets see how to iterate over the first 3 characters of string

# Iterate over the first three elements of string for elem in sampleStr[0:3:1] : print(elem)
**** Iterate over a portion of string only **** H e l

Iterate over a string by skipping characters

print("**** Iterate over string by skipping every 2nd characters ****") # Iterate over a string with 2 characters at a time for elem in sampleStr[ : : 2] : print(elem)
**** Iterate over string by skipping every 2nd characters **** H l o !

Iterate over string in backward / reverse direction using slicing

In the slicing operator [] i.e.

string[start: stop : step size]

If we skip the start and stop index, then it will use the whole string for generating sub string. But if we pass step size as -1 then it will iterate over the current string in backward direction to generate a new string, that is the reverse of original string. Then iterate over this reversed string i.e.

print("**** Iterate over string in reverse using slice operation****") for elem in sampleStr[ : :-1]: print(elem)

It will print the string contents in reverse order :

**** Iterate over string in reverse using slice operation**** ! ! o l l e H

Iterate over string in reverse using indexing :

Instead of generating a new reversed string and then iterating over that we can iterate over the current string in backward direction using indexing i.e.

print("**** Iterate over string in reverse****") i = len(sampleStr) - 1 while i >= 0 : print(sampleStr[i]) i = i - 1

It will print the string contents in reverse order

or we can use negative indexing to iterate over a string in backward direction i.e.

print("**** Iterate over string in reverse using negative indexing****") i = 1 while i 

Complete example is as follows,

def main(): sampleStr = "Hello!!" print("**** Iterate over string using for loop****") for elem in sampleStr: print(elem) print("**** Iterate over string with index using range() ****") for i in range( len(sampleStr) ): print(sampleStr[i]) print("**** Iterate over a portion of string only ****") # Iterate over the first three elements of string for elem in sampleStr[0:3:1] : print(elem) print("**** Iterate over string by skipping every 2nd characters ****") # Iterate over a string with 2 characters at a time for elem in sampleStr[ : : 2] : print(elem) print("**** Iterate over string in reverse using slice operation****") for elem in sampleStr[ : :-1]: print(elem) print("**** Iterate over string in reverse****") i = len(sampleStr) - 1 while i >= 0 : print(sampleStr[i]) i = i - 1 print("**** Iterate over string in reverse using negative indexing****") i = 1 while i 
**** Iterate over string using for loop**** H e l l o ! ! **** Iterate over string with index using range() **** H e l l o ! ! **** Iterate over a portion of string only **** H e l **** Iterate over string by skipping every 2nd characters **** H l o ! **** Iterate over string in reverse using slice operation**** ! ! o l l e H **** Iterate over string in reverse**** ! ! o l l e H **** Iterate over string in reverse using negative indexing**** ! ! o l l e H

Источник

How to Iterate over a String in Python

In this tutorial, you will find out different ways to iterate strings in Python. You could use a for loop, range in Python, a slicing operator, and a few more methods to traverse the characters in a string.

Multiple Ways to Iterate Strings in Python

The following are various ways to iterate the chars in a Python string. Let’s first begin with the for loop method.

Using for loop to traverse a string

It is the most prominent and straightforward technique to iterate strings. Follow the below sample code:

""" Python Program: Using for loop to iterate over a string in Python """ string_to_iterate = "Data Science" for char in string_to_iterate: print(char)

The result of the above coding snippet is as follows:

Python range to iterate over a string

Another quite simple way to traverse the string is by using the Python range function. This method lets us access string elements using the index.

""" Python Program: Using range() to iterate over a string in Python """ string_to_iterate = "Data Science" for char_index in range(len(string_to_iterate)): print(string_to_iterate[char_index])

The result of the above coding snippet is as follows:

How to use the slice operator to iterate strings partially

You can traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and we can iterate over it partially.

# Slicing Operator string [starting index : ending index : step value]

To use this method, provide the starting and ending indices along with a step value and then traverse the string. Below is the example code that iterates over the first six letters of a string.

""" Python Program: Using slice [] operator to iterate over a string partially """ string_to_iterate = "Python Data Science" for char in string_to_iterate[0 : 6 : 1]: print(char)

The result of the above coding snippet is as follows:

You can take the slice operator usage further by using it to iterate over a string but leaving every alternate character. Check out the below example:

""" Python Program: Using slice [] operator to iterate over a specific parts of a string """ string_to_iterate = "Python_Data_Science" for char in string_to_iterate[ : : 2]: print(char)

The result of the above coding snippet is as follows:

Traverse string backward using the slice operator

If you pass a -ve step value and skip the starting as well as ending indices, then you can iterate in the backward direction. Go through the given code sample.

""" Python Program: Using slice [] operator to iterate string backward """ string_to_iterate = "Machine Learning" for char in string_to_iterate[ : : -1]: print(char)

The result of the above coding snippet is as follows:

g n i n r a e L e n i h c a M

Using indexing to iterate strings backward

The slice operator first generates a reversed string, and then we use the for loop to traverse it. Instead of doing it, we can use the indexing to iterate strings backward.

""" Python Program: Using indexing to iterate string backward """ string_to_iterate = "Machine Learning" char_index = len(string_to_iterate) - 1 while char_index >= 0: print(string_to_iterate[char_index]) char_index -= 1

The result of the above coding snippet is as follows:

g n i n r a e L e n i h c a M

Alternatively, we can pass the -ve index value and traverse the string backward. See the below example.

""" Python Program: Using -ve index to iterate string backward """ string_to_iterate = "Learn Python" char_index = 1 while char_index 

The result of the above coding snippet is as follows:

Summary – Program to iterate strings char by char

Let’s now consolidate all examples inside the Main() function and execute from there.

""" Program: Python Program to iterate strings char by char """ def Main(): string_to_iterate = "Data Science" for char in string_to_iterate: print(char) string_to_iterate = "Data Science" for char_index in range(len(string_to_iterate)): print(string_to_iterate[char_index]) string_to_iterate = "Python Data Science" for char in string_to_iterate[0 : 6 : 1]: print(char) string_to_iterate = "Python_Data_Science" for char in string_to_iterate[ : : 2]: print(char) string_to_iterate = "Machine Learning" for char in string_to_iterate[ : : -1]: print(char) string_to_iterate = "Machine Learning" char_index = len(string_to_iterate) - 1 while char_index >= 0: print(string_to_iterate[char_index]) char_index -= 1 string_to_iterate = "Learn Python" char_index = 1 while char_index 

The result of the above coding snippet is as follows:

D a t a S c i e n c e D a t a S c i e n c e P y t h o n P t o _ a a S i n e g n i n r a e L e n i h c a M g n i n r a e L e n i h c a M n o h t y P n r a e L

Источник

Iterate over characters of a string in Python

In this article, we will learn about iterating/ traversing over characters of a string in Python 3.x. Or earlier.

The string is a collection of characters which may contain spaces, alphabets or integers. They can be accessed using indexes or via references . Some commonly implemented methods are shown below.

Method 1 − The direct itertor without indexing

Example

string_inp = "tutorialspoint" # Iterate over the string for value in string_inp: print(value, end='')

Method 2 − The most common way using index based access

Example

string_inp = "tutorialspoint" # Iterate over the string for value in range(0,len(string_inp)): print(string_inp[value], end='')

Method 3 − The enumerate type

Example

string_inp = "tutorialspoint" # Iterate over the string for value,char in enumerate(string_inp): print(char, end='')

Method 4 − Access using negative indexes

Example

string_inp = "tutorialspoint" # Iterate over the string for value in range(-len(string_inp),0): print(string_inp[value], end='')

Method 5 − Access via slicing methods

Example

string_inp = "tutorialspoint" # Iterate over the string for value in range(0,len(string_inp)): print(string_inp[value-1:value], end='') print(string_inp[-1:])

The ouptut produced by all 5 methods are identical and displayed below.

Output

Conclusion

In this article, we learnt about iteration/traversal over elements of a list. We also learnt about various ways of traversal.

Источник

Оцените статью