-1

I've been given the task to create a function that takes a string and does the following:

  • replaces each tab with a space
  • turns all letters lowercase
  • removes characters: !@#$%^&*()_+-=[]{}\|`~;:'"<>?,./

I already cracked the lowercase part by using msg.lower(), but I'm mostly stuck on the tabs to spaces part.

Any suggestions?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
ChrisAngj
  • 305
  • 3
  • 11

1 Answers1

1

You need to use series of re.sub functions.

>>> def clean(s):
        return re.sub(r'[-!@#$%^&*()_+=\[\]{}\|`~;:\'"<>?,./]', '',re.sub(r'\t', ' ', s)).lower()

>>> clean('FOO[sdFD]-+()!-')
'foosdfd'
>>> clean('Music    [()]-+~:;"  @#%&*Foo')
'music  foo'

Explanation:

  • re.sub(r'\t', ' ', s) would turn all the tabs to spaces.
  • re.sub(r'[-!@#$%^&*()_+=[]{}\|`~;:\'"<>?,./]', '',re.sub(r'\t', ' ', s)) removes all the mentioned special chars from the resultant string.
  • .lower() helps to turn all uppercase letters to lowercase letters.
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274