Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Create string with for-loop

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

like image 851
Thomas Bengtsson Avatar asked Jun 03 '26 16:06

Thomas Bengtsson


1 Answers

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
like image 92
Neil Avatar answered Jun 06 '26 04:06

Neil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!