Loop through a string in Python
String is sequence of characters, each characters can be accessed using index. We can loop through the String and extract the characters each at a time.
for loop in string python
The 'for' loop in Python is different form the 'for' loop in the other programming languages.
In Python, the 'for' loop does not require any update to be done. It automatically update after each iteration.
Python 'for' loop syntax
Example
Input
for loop through a string with range() method
Loop over a string, like above can be done with the range() method.
Program
Here we are using the iter() method to put all the characters in one list and then accessing each element of the list, which are the characters of the string.
It's another way, that I found to access characters from a string.
Program
Input
Output
Program
Input
Output
Program
Input
b = "Hello world!"'for' loop through a list with enumerate() method
The enumerate() method enumerates the string, with numbers.
Following is an example to enumerate the string.
Program
Input
b = "Python"Output
Here is an example, how you can fetch the content, got after enumerating the string. Both, characters and the enumerated value.
Program
Input
for i, j in list(enumerate(b)):
print("Index: ", i, " Value: ", j)
Iterating through a string Using List comprehension
By using the concept of list comprehension we can loop through a string, and can store each character in a list.
Here is how you can loop through a string using list comprehension.
Program
Input
Output
Conditional list comprehension with a string
Condition is placed at the end, if the condition is True then only the expression is executed.
Here is an example, which will not print the character 'l', it will print all the characters in the string except 'l'.
Program
Input
Output
Function and list comprehension with a string
Introducing a function at the beginning of the list comprehension, is also possible.
Example:- Here first we define a function 'concat()', which will print all the characters passed to it except the character 'l'. And this function is used in the list comprehension, to remove character 'l' from a string.
Program
Input
Output
Post a Comment
If you have any query, feel free to ask.