Remove a word if it contains a specific letter

Viewed 425

Let's say I have a string like

test = "hello Everyone! My name is Dan."

I want to make a function that removes all the words containing a specific letter like !

Then my string would be

"hello My name is Dan."

I tried this by test.split(' '), and replace it with '' if it contains the specific letter. However, since I have quite long documents, it seems to be a little inefficient.

Is there any other simple and compact way of solving this?

Thanks in advance! =]

5 Answers

If you are doing this over a lot of entries in a series, you can do the following:

df['ser'] = df['ser'].str.replace(r'\w+[!.,]', '')

This will replace any word following any character inside the square brackets with a blank, and is a good vectorized approach for a Pandas series.

I believe the way you are doing this is the fastest way, but you might want to use some faster keywords in it. Try this:

test = "hello Everyone! My name is Dan."
words = test.split(" ")
words = [word for word in words if not "!" in word]
answer = " ".join(words)

You can use 2 methods, split and join together. So basically your function is one line only (the return statement).

  def removeChar(string , char):
      return "".join(string.split(char)) 

  result = removeChar("hello Everyone! My name is Dan.",'!')
  print (result)

Is this part of your homework? Don't cheat man, try yourself and only come here when You at least have tried ;)

Also I recommend You to use REPL, a superb great real time online interpreter for Python and other languages. Check this solution there

https://repl.it/@inGodwetrust/RealisticStridentMatch

You can make a list and put your specific letter in it and then use a for to replace it with space. like this:

specific_chars = [';', ':', '!', "*"] 

test = "hello Everyone! My name is Dan."

for i in specific_chars : 
    test_string = test.replace(i, '') 

print(test_string)

use the replace method for the string i.e`txt = "hello Everyone! My name is Dan."

x = txt.replace("Everyone!", "")

print(x) `

Related