To loop over the characters of a string in Python, you can use a for loop and loop over each character in the following way.
string = "example"
for char in string:
print(char)
#Output:
e
x
a
m
p
l
e
When working with strings, the ability to work with the characters individually is valuable.
You can loop over the characters of a string variable in Python easily.
String objects are iterable in Python and therefore you can loop over a string.
To loop over the characters of a string in Python, you can use a for loop and loop over each character in the following way.
string = "example"
for char in string:
print(char)
#Output:
e
x
a
m
p
l
e
Examples of Using for char in string in Python to Loop Over String
Depending on the situation, you might find it useful to want to loop over the characters of a string.
One example of using ‘for char in string’ is if you want to check if a string contains only certain characters.
In Python, we can easily get if a string contains certain characters in a string looping over each character of the string and seeing if it is one of the given characters or not.
Below is a function which will check if a string has certain characters or not for you in a string using Python.
def containsCertainChars(string, chars):
for char in string:
if char in chars:
return True
return False
print(containsCertainChars("Hello World!", "H"))
print(containsCertainChars("Hello World!", "olz"))
print(containsCertainChars("Hello World!", "z"))
#Output:
True
True
False
Another example of using ‘for char in string’ to loop a string is to check if a string contains uppercase letters in Python.
To check if a string contains uppercase, we just need to loop over all letters in the string until we find a letter that is equal to that letter after applying the upper() function.
Below is a Python function which will check if a string contains uppercase characters.
def checkStrContainsUpper(string):
for x in string:
if x == x.upper():
return True
return False
print(checkStrContainsUpper("all letters here are lowercase"))
print(checkStrContainsUpper("We Have some uppercase Letters in this One."))
#Output:
False
True
Hopefully this article has been useful for you to learn how to loop over a string with ‘for char in string’ in Python.