How to create a string using for loop in python

As a beginner to Python I got these tasks by the teacher to finish and I'm stuck on one of them. It's about finding the consonants in a word using a for-loop and then create a string with those consonants.

The code I have is:

consonants = ["qwrtpsdfghjklzxcvbnm"]
summer_word = "icecream"

new_word = ""

for consonants in summer_word:
    new_word += consonants

ANSWER = new_word

The for-loop I get but it's the concatenation I don't really get. If I use new_word = [] it becomes a list, so I should use the ""? It should become a string if you concatenate a number of strings or characters, right? If you have an int you have to use str(int) in order to concatenate that as well. But, how do I create this string of consonants? I think my code is sound but it doesn't play out.

Regards

asked Sep 16, 2018 at 12:09

How to create a string using for loop in python

Your loop is currently just looping through the characters of summer_word. The name "consonants" you give in "for consonants..." is just a dummy variable, it doesn't actually reference consonants that you defined. Try something like this:

consonants = "qwrtpsdfghjklzxcvbnm" # This is fine don't need a list of a string.
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.

ANSWER = new_word

answered Sep 16, 2018 at 12:17

A string in Python is already a list of characters and may be treated as such:

In [3]: consonants = "qwrtpsdfghjklzxcvbnm"

In [4]: summer_word = "icecream"

In [5]: new_word = ""

In [6]: for i in summer_word:
   ...:     if i in consonants:
   ...:         new_word += i
   ...:

In [7]: new_word
Out[7]: 'ccrm'

answered Sep 16, 2018 at 12:15

Swagga TingSwagga Ting

5922 silver badges17 bronze badges

You are right, if the character is a number you must use str(int) to convert it in string type.

consonants = ["qwrtpsdfghjklzxcvbnm"]
summer_word = "icecream"

new_word = ""
vowels = 'aeiou'
for consonants in summer_word:
    if consonants.lower() not in vowels and type(consonants) != int:
        new_word += consonants
answer = new_word

Here inside the for loop you are evaluating if the 'consonants' is not a vowel and is not an int. Hope this help you.

answered Sep 16, 2018 at 12:21

SnedecorSnedecor

6411 gold badge6 silver badges13 bronze badges

The issue you have here is that you have created the variable consonants as a list with a string in it. So remove the square brackets and it should work

answered Sep 16, 2018 at 12:15

How to create a string using for loop in python

K-D-GK-D-G

1151 silver badge8 bronze badges

consonants = "qwrtpsdfghjklzxcvbnm"
summer_word = "icecream"

new_word = ""


for letter in summer_word:
    if letter in consonants:
      new_word += letter

print(new_word)

A shorter one would be

consonants = "qwrtpsdfghjklzxcvbnm"
summer_word = "icecream"

new_word = ""

new_word = [l for l in summer_word if l in consonants]
print("".join(new_word))

answered Sep 16, 2018 at 12:21

How to create a string using for loop in python

yoonghmyoonghm

3,5201 gold badge28 silver badges44 bronze badges


Python For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Example

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

Try it Yourself »

The for loop does not require an indexing variable to set beforehand.


Looping Through a String

Even strings are iterable objects, they contain a sequence of characters:

Example

Loop through the letters in the word "banana":

for x in "banana":
  print(x)

Try it Yourself »


The break Statement

With the break statement we can stop the loop before it has looped through all the items:

Example

Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

Try it Yourself »

Example

Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    break
  print(x)

Try it Yourself »



The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue with the next:

Example

Do not print banana:

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  if x == "banana":
    continue
  print(x)

Try it Yourself »


The range() Function

To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):

Example

Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):
  print(x)

Try it Yourself »


Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

Example

Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
  print(x)
else:
  print("Finally finished!")

Try it Yourself »

Note: The else block will NOT be executed if the loop is stopped by a break statement.

Example

Break the loop when x is 3, and see what happens with the else block:

for x in range(6):
  if x == 3: break
  print(x)
else:
  print("Finally finished!")

Try it Yourself »


Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example

Print each adjective for every fruit:

adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
  for y in fruits:
    print(x, y)

Try it Yourself »


The pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error.




Can we use for loop for string 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.

How do you add a string to a for loop?

Python concatenate strings in for loop To concatenate strings we will use for loop, and the “+ ” operator is the most common way to concatenate strings in python.

How do you pass a string in a for loop in Python?

You can traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and thus allows to iterate over it partially. To use this method, provide the starting and ending indices along with a step value and then traverse the string.

How do you create a string in Python?

To create a string, put the sequence of characters inside either single quotes, double quotes, or triple quotes and then assign it to a variable. You can look into how variables work in Python in the Python variables tutorial. For example, you can assign a character 'a' to a variable single_quote_character .