+ 2
How can I using module "re" delete all symbols except whitespaces and letters?
I think, i should use something like '[A-z]' and '\s', but i don't know how to use them in conjunction.
6 ответов
+ 4
Whenever I see someone ask that sort of question I want to ask back:
Why do you want to use a machine gun to kill a mosquito?
You can just filter your string for letters and space with regular string methods, without using re.
Does your teacher insist on you using re?
string = ''.join(
l for l in string
if l.isalpha() or l.isspace()
)
+ 2
import re
line = re.sub('[^\sA-Za-z0-9]', '', line)
+ 2
I think that study and practice of regular expression is to be encouraged, and that it could be very efficient in some context...
Sure, for just one short string it's seems to be a machine gun to kill a mosquito, but who can do more could do less ^^ (and re solution is quite 1.5 to 2 times quickest than filter and join string, so for many and/or long strings it will save some time)
import re
asr = re.compile(r'[^a-z\s]+',re.I)
alphasp = lambda s: asr.sub('',s)
+ 2
visph, i totally agree with you. Re is more powerful tool as i thought earlier. And understanding all of settings require calming and time. But finally you should get good experience and knowledge.
By the way, method of HongFu works. Little bit later i will check methods that you proposed above.
+ 2
Don't want to tell anybody not to study RegEx btw.
My impression is, though, that quite a few learners here use re because they saw in the tutorial that there is such a thing, but they don't know yet that there are also basic string methods.
We should choose the best tool for the task, but as learners we should get accustomed to the different tools, to be able to choose.
Starting with the advanced methods before the regular stuff (whoops, pun) seems to be putting the cart before the horse.
+ 1
It depends on mosquitos size. Ha-ha! No, because i teach myself and using re is one of ways to resolve my task. But i try to use your suggestion. Thanks