Python loop for string

How to Iterate a String in Python using For Loop

How to iterate a string in Python using For loop ? You can iterate over each character of a string using multiple ways of Python. The string is a basic datatype of Python that contains a collection of characters within a single or double quotes. In this article, I will explain while iterating a string using for loop, how we can get each character of the given string in multiple ways. And also explains using reversed() function how we can iterate over the string and get each character in reverse order.

1. Quick Examples of Iterating String using For Loop

Following are quick examples of how to iterate a string using for loop.

Читайте также:  Что такое html ucoz

What is String in Python?

A string in Python is a data type and data structure that is used to store sequences of characters and manipulate text-based data. They are represented by a set of characters enclosed in quotes, either single or double.

Python String datatype support indexing, which allows you to access individual characters within a string. This can be useful for tasks such as parsing and extracting information from strings.

2. Iterate Over a String using Python For Loop

You can use for loop to iterate over a string and get each character of the string. Let’s take a string and iterate it using for loop, for every iteration to get each character presented in the string.

Python for loop string

3. Iterate String using For Loop by Index

While iterating over the string using for loop, you can get the corresponding index of each character of a given string. You can use the Python range() function to get the range of the sequence and use the len() function to get the length of the Passed object. You can iterate range(0, len(str)) using for loop, for every iteration to get the index and corresponding character of the string.

Python for loop string

Alternatively, iterate over a string by index using enumerate() function. Python enumerate() function is a built-in function and is used to iterate a sequence and return the index of each item presented in the sequence. You can iterate enumerate(str) using for loop, for every iteration to get the index and corresponding character of the string.

4. Iterate String using Python For Loop in Reverse Order

Alternatively, you can use for loop to iterate over the string and get each character in reverse order. You can pass range(0, len(str)) into reversed() function and iterate it using for loop, for each iteration you can retrieve the index of the string in reverse order. You can use the retrieved index to access the corresponding character of a given string.

5. Iterate Selected Portion of String using For Loop

You can use the slicing technique to iterate over the selected portion of the string. Let’s use slicing to iterate over a selected portion of the string. For example,

Alternatively, you can use the itertools module to iterate over the string and get the selected part of the string in Python.

6. Iterate Python String using while loop

A while loop in Python will iterate over a given sequence of elements until a given condition is met. In this case, we will loop through a string until the given condition is met.

7. Conclusion

In this article, I have explained using for loop over a string and how we can get each character of the given string in multiple ways. And explained using reversed() function how we can iterate over the string in reverse order.

You may also like reading:

Источник

Loop Over a String in Python

Loop Over a String in Python

  1. Use the for Loop to Loop Over a String in Python
  2. Use the while Loop to Loop Over a String in Python

A string is a chain of characters, where every character is at a particular index and can be accessed individually.

In this tutorial, we loop over a string and print individual characters in Python.

Use the for Loop to Loop Over a String in Python

The for loop is used to iterate over structures like lists, strings, etc. Strings are inherently iterable, which means that iteration over a string gives each character as output.

In the above example, we can directly access each character in the string using the iterator i .

Alternatively, we can use the length of the string and access the character based on its index.

Str_value = "String" for index in range ( len ( Str_value ) ):  print ( Str_value[index]) 

The enumerate() function can be used with strings. It is used to keep a count of the number of iterations performed in the loop. It does it by adding a counter to the iterable. It returns an object containing a list of tuples that can be looped over.

for i , j in enumerate("string"):  print(i , j)  

Use the while Loop to Loop Over a String in Python

The while loop is used just like the for loop for a given set of statements until a given condition is True. We provide the string’s length using the len() function for iterating over a string.

In the while loop, the upper limit is passed as the string’s length, traversed from the beginning.
The loop starts from the 0th index of the string till the last index and prints each character.

Str_value = "String" i=0; while(i  len(Str_value)):  print(Str_value[i])  i=i+1 

Источник

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

Источник

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