Python,join() function, adding space between words

10,588

Solution 1

You have an extra space when you join your asterisks:

def censor(text, word):
    text = text.split(" ")
    asterisks=[]
    text_with_asterisks=[]

    for item in text:
        if item not in word:
            text_with_asterisks.append(item)
        else:
            asterisks=[]
            for letter in word:
                asterisks.append("*")

            text_with_asterisks.append(''.join(asterisks)) #here's the culprit
    return (" ".join(text_with_asterisks))

censor("hey hey hey", "hey") outputs what you want ('*** *** ***')

I just pointed out your mistake, but surely there's a more elegant and efficient way to do what you want.

Solution 2

Here is the simplest solution

text.replace(word, "*" * len(word))

Solution 3

Regex method of doing this -

import re
def censor(text,word):
    return re.sub(r'\b(?i){0}\b'.format(re.escape(word)),'*' * len(word), text)

Example/Demo -

>>> censor('hey hey they hey','hey')
'*** *** they ***'

>>> censor('hey hey they Hey','hey')
'*** *** they ***'

Solution 4

You have spaces between every * in the word, and additional spaces between the words, so I think, you only want spaces between words:

def censor(text, word):
    return ' '.join('*'*len(word) if word==item else item for item in text.split())

Solution 5

Simple solution,

>>> text = "hey hey hey"
>>> "***".join(text.split("hey"))
'*** *** ***'

Or

 >>> text = "hey hey they Hey','hey"  
 >>> " ".join([ '***' if word.lower() == 'hey' else word
 ... for word in text.replace("'","").replace(","," ").split()])
 '*** *** they *** ***'
Share:
10,588

Related videos on Youtube

WhiteM
Author by

WhiteM

Updated on September 15, 2022

Comments

  • WhiteM
    WhiteM about 1 year

    I need to write a function that takes two strings (text and word) and returns the text with the chosen word replaced with asterisks (the number of asterisks should correspond to the number of letters in the censored word.).

    For example:

    if text="hey hey hey" and word="hey" the returned text should be:

    '*** *** ***'
    

    Here is my code:

    def censor(text,word):
        text = text.split(" ")
        asterisks=[]
        text_with_asterisks=[]
    
        for item in text:
            if item not in word:
                text_with_asterisks.append(item)
            else:
                asterisks=[]
                for letter in word:
                    asterisks.append("*")
    
                text_with_asterisks.append(' '.join(asterisks))
        return (" ".join(text_with_asterisks))
    

    The code works but it returns:

     ********* 
    

    and not

    *** *** ***. 
    

    Once I use the line:

    return ("_".join(text_with_asterisks))
    

    instead I get:

    '***_***_***'
    

    I don't understand why the " " is ignored and how can I add a space between the words.

    Thanks!

    • TheBlackCat
      TheBlackCat about 8 years
      I am not getting the same result as you. I am getting '* * * * * * * * *. This is due to the text_with_asterisks.append(' '.join(asterisks)) line. If I change the ' ' there to '', I get '*** *** ***'.
    • Peter Wood
      Peter Wood about 8 years
      You can multiply strings: '*' * len(word)
    • skyking
      skyking about 8 years
      You have to use join twice, first to join the asterisks that replace each word which, then again to join the asterisk replaced words. Which you have done, but you need to first time use "" as separator and the next time use " " as separator.
    • skyking
      skyking about 8 years
      In addition your code does not do what you might expect. It's actually looking for words that are a part of the word. Calling cencor("he", "hey") you'll get *** because he is a part of hey and three asterisk because hey has three letters.
    • YvesQuemener
      YvesQuemener about 8 years
      The first part of your message suggests that there is a single word that you want to replace but your example program seems to imply that you actually have a list of words you want to censor. Maybe you should make that clear. Otherwise, clever one liners like Adem Öztaş' are probably what you want.
  • tobias_k
    tobias_k about 8 years
    This will also replace the word if it is part of another word, e.g. it will replace "ass" in "masses". Better use regex with word boundary markers.
  • dmr
    dmr about 8 years
    text.replace(" " + word + " " , "*" * len(word)) - doest it help?
  • tobias_k
    tobias_k about 8 years
    What about punctuation then?
  • WhiteM
    WhiteM about 8 years
    Thank you very much. It works just fine now. Unfortunately, I am not allowed to use Regex method or alike but I do agree there is more elegant way to solve it.
  • secelite
    secelite almost 7 years
    While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.