Search code examples
python-3.xfor-loopstring-concatenation

Concatenating string outputs of a for loop in Python 3


I have a code which, after a nested for loop, provides me with a unique string in each iteration. I want to find a way to concatenate those outputs so that my final line is a single string of those unique strings. Ignoring how ugly and inefficient this code is, what steps can I take to achieve the desired result?

VOWELS = ('a','e','i','o','u','A','E','I','O','U')

ad = "Desirable unfurnished flat in quiet residential area"
# remove all vowels, unless the word starts with a vowel

def is_vowel(c):
    return c in VOWELS

def mod3(ad):
    testAd =ad.split()
    for word in testAd:
        modAd = ""
        i = 0
        for char in word:
            if i == 0:
                modAd += char
            elif not is_vowel(char):
                modAd += char
            i+=1
        print(modAd)

mod3(ad)

my output for this code: enter image description here

Otherwise, when I modify my code to look like this:

enter image description here

But my output is: enter image description here

I don't believe a .join() would work here as it's not a list type. And I can't figure out where to put a string concat + anywhere without my for loop going bonkers. Any advice?


Solution

  • You can create a string result where you can concatenate your each iteration result and print that. You need to add spaces after each addition of words. So, append + " " to your result variable as well.

    def mod3(ad):
        result = ""
        testAd =ad.split()
        for word in testAd:
            modAd = ""
            i = 0
            for char in word:
                if i == 0:
                    modAd += char
                elif not is_vowel(char):
                    modAd += char
                i+=1
            result += modAd + " "
        print(result)
    

    Second option: This is my take on it:

    def mod4(ad):
        result = ""
        testAd =ad.split()
        for word in testAd:
              for i, char in enumerate(word):
                  if i == 0:
                      result += char
                  if i > 0 and char not in VOWELS:
                      result += char
              result += " "
        print(result)