+ 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
8 Respostas
+ 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.
+ 3
As HonFu suggested.
https://code.sololearn.com/cm9aTdDOyTV1/?ref=app
+ 3
You could use a comprehension:
return ' '.join(s for s in stringList if s)
+ 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.
+ 1
def cleanup(stringList):
cleaned = ""
for word in stringList:
if word:
cleaned += word
return ''.join(cleaned)
print(cleanup(["A", "", "B", "", "C"]))
# ABC
+ 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.
+ 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
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