2

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

  • You can use the same technique as this post: https://stackoverflow.com/questions/18173555/filtering-characters-from-a-string – vaeng Feb 22 '20 at 10:25

1 Answers1

2

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • For those who don't read RegEx like English, the key function here is documented at https://docs.python.org/3.7/library/re.html#re.sub, and RegEx as used in Python is documented at https://www.w3schools.com/python/python_regex.asp – Post169 Aug 14 '20 at 16:04