Python - Create string with for-loop

18,026

Solution 1

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

Solution 2

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.

Solution 3

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'
Share:
18,026

Related videos on Youtube

Thomas Bengtsson
Author by

Thomas Bengtsson

Updated on June 04, 2022

Comments

  • Thomas Bengtsson
    Thomas Bengtsson almost 2 years

    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