+ 1

The .join() function Python

Hello, Trying to get this function to take a list of strings and return a joined string(separated by space), without printing out the EMPTY strings in the list. #The cleanup function def cleanup(stringList): cleaned = "" for word in stringList: cleaned += word return ' '.join(stringList) #test print(cleanup(["cat", "er", "pillar"])) => cat er pillar print(cleanup(["cat", "", "er", "", "pillar"])) => cat er pillar #this keeps printing the spaces as well, I am missing something in the function. It should return the string without the empty strings. Thank you

11th Mar 2020, 11:44 PM
hartechworld
hartechworld - avatar
8 Answers
+ 3
The strings in your list will be glued together using the string in front of your join. You are writing ' '.join. So there'll be a space between every string. Write ''.join instead. So an empty string in the beginning. Then the strings will be glued together... with nothing in between, just as you want it.
11th Mar 2020, 11:47 PM
HonFu
HonFu - avatar
12th Mar 2020, 1:27 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
You could use a comprehension: return ' '.join(s for s in stringList if s)
12th Mar 2020, 9:55 AM
HonFu
HonFu - avatar
+ 2
Hi HonFu, Rik, Thanks for your response. The space in between the strings in not the problem. If the function receives a list name = ["Honfu", "", "Rik", "", "Wittkopp"], it should only return the non-empty strings (HonFuRikWittkopp), without adding the empty strings "" to the output. (with or without spaces) You could run this on your IDE to see what I mean, thanks for your time.
12th Mar 2020, 6:51 AM
hartechworld
hartechworld - avatar
+ 1
def cleanup(stringList): cleaned = "" for word in stringList: if word: cleaned += word return ''.join(cleaned) print(cleanup(["A", "", "B", "", "C"])) # ABC
12th Mar 2020, 7:24 AM
Diego
Diego - avatar
+ 1
Hi Haruna Umar A I put that sample you gave into the code and it works. Please check and let me know if I am misunderstanding something.
12th Mar 2020, 7:34 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
Hello Diego, print(cleanup(["A", "", "B", "", "C"])) will give ABC for sure. but let's say we have def cleanup(stringList): cleaned = "" for word in stringList: if word: cleaned += word return " ".join(cleaned) #mind the space used before .join() If you pass: print(cleanup(["", "Diego", "", "Expert", "", "", "Diego"])) Can you make the function return: Diego Expert Diego? NOT DiegoExpertDiego OR D i e g o E x p e r t D i e g o
12th Mar 2020, 9:50 AM
hartechworld
hartechworld - avatar
0
The problem in your code is in (cleaned += word) Because you are concatenating all words in your list then using the " ".join(cleaned) to add a space between chars of the concatenated string cleaned should be a list to be appended if word is != " ". P.S I don't want to give the code to let you better understand
13th Mar 2020, 6:02 PM
Ilyes Embarki
Ilyes Embarki - avatar