Reputation:
Like i have string variable which has value is given below
string_value = 'hello ' how ' are - you ? and/ nice to % meet # you'
Expected result:
hello how are you and nice to meet you
Upvotes: 2
Views: 115
Reputation: 520968
You could try just removing all non word characters:
string_value = "hello ' how ' are - you ? and/ nice to % meet # you"
output = re.sub(r'\s+', ' ', re.sub(r'[^\w\s]+', '', string_value))
print(string_value)
print(output)
This prints:
hello ' how ' are - you ? and/ nice to % meet # you
hello how are you and nice to meet you
The solution I used first targets all non word characters (except whitespace) using the pattern [^\w\s]+
. But, there is then the chance that clusters of two or more spaces might be left behind. So, we make a second call to re.sub
to remove extra whitespace.
Upvotes: 2