Skip to content

For loop string Python | Example code

  • by

Using For loop in the string you can iterate over characters of a string in Python.

How to loop through the string in Python example

Simple example code of for loop is used for iterating over a sequence data string.

for i in "Hello":

    print(i)

Output:

For loop string Python

Python create string with for-loop

consonants = "qwrtpsdfghjklzxcvbnm"
summer_word = "icecream"

new_word = ""

for character in summer_word:  # loop through each character in summer_word
    if character in consonants:  # check whether the character is in the consonants list
        new_word += character
    else:
        continue  # Not really necessary by adds structure. Just says do nothing if it isn't a consonant.

print(new_word)

Output: ccrm

How to concatenate to a string in a for loop in Python?

Answer: Use the join function to concatenate string.

res = ''.join(['first', 'second', 'other'])
print(res)

That’s not how you do it.

>>> ''.join(['first', 'second', 'other'])
'firstsecondother'

If you do it in a for loop, it’s going to be inefficient as string “addition”/concatenation doesn’t scale well (but of course it’s possible):

mylist = ['first', 'second', 'other']
s = ""
for item in mylist:
    s += item

print(s)

Output: firstsecondother

Do comment if you have any doubts and suggestions on this Python for loop topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading