You can use this pattern, too, with regex:
import re
a = '''hello? there A-Z-R_T(,**), world, welcome to python.
this **should? the next line#followed- by@ an#other %million^ %%like $this.'''
for k in a.split("\n"):
print(re.sub(r"[^a-zA-Z0-9]+", ' ', k))
# Or:
# final = " ".join(re.findall(r"[a-zA-Z0-9]+", k))
# print(final)
Output:
hello there A Z R T world welcome to python
this should the next line followed by an other million like this
Edit:
Otherwise, you can store the final lines into a list:
final = [re.sub(r"[^a-zA-Z0-9]+", ' ', k) for k in a.split("\n")]
print(final)
Output:
['hello there A Z R T world welcome to python ', 'this should the next line followed by an other million like this ']
Answer from Chiheb Nexus on Stack OverflowYou can use this pattern, too, with regex:
import re
a = '''hello? there A-Z-R_T(,**), world, welcome to python.
this **should? the next line#followed- by@ an#other %million^ %%like $this.'''
for k in a.split("\n"):
print(re.sub(r"[^a-zA-Z0-9]+", ' ', k))
# Or:
# final = " ".join(re.findall(r"[a-zA-Z0-9]+", k))
# print(final)
Output:
hello there A Z R T world welcome to python
this should the next line followed by an other million like this
Edit:
Otherwise, you can store the final lines into a list:
final = [re.sub(r"[^a-zA-Z0-9]+", ' ', k) for k in a.split("\n")]
print(final)
Output:
['hello there A Z R T world welcome to python ', 'this should the next line followed by an other million like this ']
I think nfn neil answer is great...but i would just add a simple regex to remove all no words character,however it will consider underscore as part of the word
print re.sub(r'\W+', ' ', string)
>>> hello there A Z R_T world welcome to python
python - Remove all special characters, punctuation and spaces from string - Stack Overflow
How do I remove remove stuff like (. , ' *) from a string?
regex - How to remove all special characters except spaces and dashes from a Python string? - Stack Overflow
python - remove special character from string, not replace them with space - Stack Overflow
This can be done without regex:
>>> string = "Special $#! characters spaces 888323"
>>> ''.join(e for e in string if e.isalnum())
'Specialcharactersspaces888323'
You can use str.isalnum:
S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise.
If you insist on using regex, other solutions will do fine. However note that if it can be done without using a regular expression, that's the best way to go about it.
Here is a regex to match a string of characters that are not a letters or numbers:
[^A-Za-z0-9]+
Here is the Python command to do a regex substitution:
re.sub('[^A-Za-z0-9]+', '', mystring)
I have a string:
"Bob 'hit' a ball, the hit BALL flew far after it was hit."
And I want to replace the word 'hit' by 'sample'.
How do I do that when the word gets immediately followed/preceded by stuff like (. , ' *)
Edit: I know using replace() will work but I don't know what special characters there will be in the string. Some strings had characters like ( - [ / + .
You are actually trying to "slugify" your string.
If you don't mind using a 3rd party (and a Python 2 specific) library you can use slugify (pip install slugify):
import slugify
string = "Web's GReat thing-ok"
print slugify.slugify(string)
>> 'webs_great_thing-ok'
You can implement it yourself.
All of slugify's code is
import re
import unicodedata
def slugify(string):
return re.sub(r'[-\s]+', '-',
unicode(
re.sub(r'[^\w\s-]', '',
unicodedata.normalize('NFKD', string)
.encode('ascii', 'ignore'))
.strip()
.lower())
Note that this is Python 2 specific.
Going back to your example, You can make it a one-liner. Whether it is Pythonic enough is up to you to decide (note the shortened range A-z instead of A-Za-z):
import re
my_string = "Web's GReat thing-ok"
new_string = re.sub('[^A-z0-9 -]', '', my_string).lower().replace(" ", "_")
UPDATE There seems to be more robust and Python 3 compatible "slugify" library here.
A one-liner, as requested:
>>> import re, unicodedata
>>> value = "Web's GReat thing-ok"
>>> re.sub('[\s]+', '_', re.sub('[^\w\s-]', '', unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore').decode('ascii')).strip().lower())
u'webs_great_thing-ok'
You can add an space after the caret(^), like this
In [1]: re.sub(r"[^ a-zA-Z0-9]+",'',input_string)
# ^ space here
Out[1]: 'abcd efgh ijk LM'
If you also want to remove trailing or leading whitespaces you can use the strip method.
In [2]: ' Hello '.strip()
Out[2]: 'Hello'
You can replace every special character (excluding space) by empty character:
re.sub(r"[^a-zA-Z0-9 ]+", '', input_string)