Search code examples
python-3.xstringspecial-characters

remove special character from string in python


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


Solution

  • 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.