Censor *Exclusively using Regular Expressions Module*


#1



Oops, try again. Your function fails on censor("hey hey hey","hey"). It returns "he* he* he*" when it should return "*** *** ***".


I want to use the re python module, to solve this in a different fashion. But something about my code, only replaces the last letter instead of the entire word. What am I doing wrong?


import re

def censor(text, word):
    for word in text:
        string = re.sub(word, ('*' * (len(word))), text)
    return string

text = 'hey hey hey'
word = 'hey'
print censor(text, word)

FINAL VERSION:

import re

def censor(text, word):
    return re.sub(word, '*' * len(word), text)

Test:

text = 'hey hey hey'
text1 = '1heyr heydg fhey'
word = 'hey'
print censor(text, word)
print censor(text1, word)


#2

text is a string, so word in the loop is a single character. Add print word statement to the body of the for loop to observe this.

You can split text into list of words by using split method.

Quite frankly, I do not understand the idea behind this code. The sub method says that you want to replace only the last word of text, no matter if it should be censored or not. Do not use the same name for parameter and the iterative variable.


#3

Thanks for the word choice advice, I just realized that in a different exercise.

I thought that the behaviour of replacing just the last character of the word was due to this:

yet, I replaced it with this

string = re.sub(word, '*', text)

And I still get the same behaviour.

I'd really like a solution using regular expressions.

P.S: I added the print and it does indeed grabs a single character.


#4

Why does it only replace the last character, that's the confusing and weird thing about it. That I want to understand as well


#5

Nvm, I got it :slight_smile:

import re

def censor(text, word):
    for i in text:
        string = re.sub(word, '*' * len(word), text)
    return string

text = 'hey hey hey'
word = 'hey'
print censor(text, word)

You were right about changing the iterate variable


#6

Now there's a new problem if I replace the word with something else, like

word = 'heyl'

This happens:

> hey hey hey
> None

How do I solve this bug in my code??

And the exercise still passes, which should not!


#7

If I understand correctly, the correct output for censor('hey hey hey', 'heyl') is hey hey hey, so everything is ok :slight_smile:

But I still do not understand why you want to use a loop, variable i is unused. Why not:

import re

def censor(text, word):
	return re.sub(word, '*' * len(word), text)

?


#8

Thanks, I still got a long way to go


#9

You're welcome :slight_smile: Well, you are in the right place to learn a bit more :wink:


#10

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