-3
"I am a human"

From the above string I want to remove the letter "a" so that the string becomes:

"I am human"

I used the following code and it works perfectly fine.

plural = input("Enter a string: ")
processed = plural.split()

processed.remove("a")

However, if the sentence doesn't have "a" in it it ends up with an error.

"I am not an elephant"

In this case I want the program to ignore it. How do I do it?

vardos
  • 334
  • 3
  • 13

2 Answers2

2

Its just a split on the text where the pattern matches. regex is much better to use though.

" ".join("I am a human".split(" a "))

OR

"I am a human".replace(" a "," ")
Akshay Hazari
  • 3,186
  • 4
  • 48
  • 84
  • 1
    Answer that have only code and no explanation are not useful, please state what your code does and in what way it helps OP – Tim Nov 24 '15 at 09:02
1

According to the doc the remove() method is raising an error when there is no such value in the list.

As you know that this might happend, you could just catch the exception:

try:
    processed.remove("a")       
except ValueError:
    pass # happens.

However it would be better to use regular expressions, for example re.sub():

This won't break when something unexpected will be inputed in plural:

plural = "I am a human"
value = re.sub(' a ', ' ', plural) # Replace "space + 'a' letter + space" with one space
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162