Just like join() uses the string it’s attached to to determine how to join together the string you provide in parentheses, split() does the same for splitting a string passed to it.
For example, if we have my_words_split = " ".split("first second third last"), the resulting list stored in my_words_split will be ["first", "second", "third", "last"].
We’ve done lots of work with lists, so the rest of this function is up to you, but remember to " ".join() your words back together at the end if you take this route!
This is a bit confusing…
When I try to split my text with the method shown above, it results in: [" “].
So I googled it and tried the method suggested there: text.split(” ").
This worked great. The join function works as described here.
def censor(text, word):
words = text.split()
result = ''
stars = '*' * len(word)
count = 0
for i in words:
if i == word:
#Why not words[i] = stars? It would be one conditional, and i would be
#equal to the index of word at the time that the conditional triggers.
#Can someone explain why count is needed?
words[count] = stars
count += 1
#result joins a space to words, but result wasn't modified in the
#conditional or for loop, so I don't get this part
result =' '.join(words)
return result
print censor("this hack is wack hack", "hack")
Although it works, the solution’s reference to joining of result doesn’t make sense to me.
See comments in code for more info.
Also, I was thinking “words[i] = stars” would make more sense since i would end up at the index where it discovered the word.
I fail to understand two things about the answer provided in the course.
What is the point of line 3, where it says "result = ’ ’ ". When I delete it, the function still works fine.
Also, what is the parentheses used for with the split method? i.e. text.split() When I put any string in the parentheses, the text is put in a list, but it is not being split anymore.
str.split() is a string method, and like any function cannot be invoked without the parens. If nothing is written in the parens (the argument) then the default argument is ' ' (a space character) so that it splits out the words without whitespace.
The argument is called the separator string and specifies what characters to target as the split point.
"The rain in Spain falls mainly in the plains".split()
What I specifically don’t understand about the .split method is why, when I use any other string as the separator string, the sentence is not actually being split. It’s just being put into the list as one item.
As for result = ’ ', I don’t really understand why they’ve initialized it as a string object in line 3, if the function works the same without line 3. Is it just good practice to do that for all variables that will appear as part of the function?