Censor 10/15


#1
def censor(text, word):
    words = text.split()
    result = ''
    stars = '*' * len(word)
    count = 0
    for i in words:
        if i == word:
            words[count] = stars
        count += 1
    result =' '.join(words)

    return result

here
i == word:
here i is the single character where as word is a string how can they be compared


#2

are you certain of that? Here is your code with function call and print statement:

def censor(text, word):
    words = text.split()
    result = ''
    stars = '*' * len(word)
    count = 0
    for i in words:
        print i
        if i == word:
            words[count] = stars
        count += 1
    result =' '.join(words)

    return result

print censor("hey hey hey", "hey")

as you can see, i are words, not individual letters. You are looping over words, which is an array, so i will contain elements from array

if we where looping over string, what you should said would be true


#3

but then what does split do?


#4

thankfully, we have documentation for that:

https://docs.python.org/2/library/stdtypes.html#str.split


#5

Since most things can be solved any number of ways, I went with:

def censor(text,word):
  result = ""
  censored = "*" * len(word)
  pieces = text.split(word)
  result = censored.join(pieces)
  return result

It seems to work - any reason why a loop would be a preferred solution?


#6

because your code has a corner case:

def censor(text,word):
  result = ""
  censored = "*" * len(word)
  pieces = text.split(word)
  result = censored.join(pieces)
  return result


print censor("this is easy", "is")

is of this shouldn’t be censored in my opinion. But this depends on what the program needs to do. For example, this forum has a censor function as well. We can’t type ■■■■ but if we then add one letter at the end we get hello, and that is allowed. your censor function would give use ■■■■o, now you still don’t know what that says


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.