Question

i'm trying to remove question marks from a string in python and I'm wondering what the most efficient way to do it is. I assume searching each word for a ? is not the best way. Just to clarify, I am looking to change this

"What is your name?"

to this

"what is your name"
Was it helpful?

Solution

"What is your name?".replace("?","") #this is the most clear
#or
filter(lambda x:x!= "?","What is your name?")
#or
"".join(x for x in "What is your name?" if x != "?")
#or
"What is your name?".translate(None,"?") #this is my favorite

and many more

OTHER TIPS

replace() is simple and efficient:

>>> "What is your name?".replace("?", "")
'What is your name'

In my humble opinion you should look at built-in string.replace() method.

result = "What is your name?".replace('?', '')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top