How can I use split( ) to make censor?


#1

Question

How can I use split( ) to make censor?

Answer

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!


FAQ: Learn Python - Practice Makes Perfect - censor
#2

A post was split to a new topic: Censor replacing using index


#3

2 posts were split to a new topic: Censor


#7
count = 0
for i in words:
    if i == word:
        words[count] = stars
    count += 1
result =' '.join(words)

Someone explain the count variable, how it works? Please.


#8

count is a variable to keep track of the index, so we can use it to update elements in words list

i would have named the variable index, not count.


#9

Yep! I understand …


#13

A post was split to a new topic: Function prints correct message but not working


#14

4 posts were split to a new topic: Censor


#18

A post was split to a new topic: Censor


#19

Hi,

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.

Can you explain this behavior?
Thx


#20

the FAQ just got how split works wrong.


#26

Your count variable corresponds to the index of each item (in the list), & the loop is traversing through each index


#27
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.


#28

you could do that, but then use range in the loop, or use a while loop and count. The only reason not to, would be to save list lookups


#29

As @stetim94 pointed out, we need to use range() to generate a list of indices. List index values must be integer.