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

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For those who don't read RegEx like English, the key function here is documented at docs.python.org/3.7/library/re.html#re.sub, and RegEx as used in Python is documented at w3schools.com/python/python_regex.asp