1

I have to create a function that takes a list of integers, strings, and booleans as an input. It is then takes the strings and prints them out as one sentence. This is my function so far:

def sentenceGenerator(a):
    newList = []
    for string in a:
        if string == str
            newList.append(string)
    print(newList)  

And this is how I use it:

sentenceGenerator(["Mulan", "and", 5, "Aladdin", "is", True, "Quality"])

I know the if statement is not correct but I don't know how else to search.

jpaugh
  • 6,634
  • 4
  • 38
  • 90
Trea704
  • 37
  • 4

5 Answers5

1

What about

source = ["Mulan", "and", 5, "Aladdin", "is", True, "Quality"]
[word for word in source if isinstance(word, str)]

and even

' '.join([word for word in source if isinstance(word, str)])

to get a single sentence?

Timothée Poisot
  • 226
  • 2
  • 10
1

In following part:

string == str

You are comparing an item with str type and since the == operation will compare the string's value the preceding statement would be False.

If you want to check the type of an object you can use isinstance() built-in function.

And as a more pyhtonic way you can use a list comprehension to get the string form your list and pass the result to str.join() function with a proper delimiter in order to join the words:

>>> ' '.join([item for item in l if isinstance(item, str)])
'Mulan and Aladdin is Quality'
Mazdak
  • 105,000
  • 18
  • 159
  • 188
0

You could use filter to find the strings and then use join to combine them like so

def sentenceGenerator(a):
    print ' '.join(filter((lambda x: type(x) is str), a)) 

sentenceGenerator(["Mulan", "and", 5, "Aladdin", "is", True, "Quality"])

Mulan and Aladdin is Quality
SirParselot
  • 2,640
  • 2
  • 20
  • 31
0

If you don't familiar with lambda you could use built-in map function:

lst = ["Mulan", "and", 5, "Aladdin", "is", True, "Quality"]
str = " ".join(map(str, lst))
Aleks Lee
  • 136
  • 1
  • 1
  • 10
0

just this -

def sentenceGenerator(a):
    newList = []
    for string in a:
        if isinstance(string, str) or isinstance(string, unicode):
            newList.append(string)
    print(newList)
Ben
  • 1,414
  • 2
  • 13
  • 18
Muthu Rg
  • 632
  • 1
  • 6
  • 18