3

Just a (hopefully) simple question.
Doing some messing around with Python and I just want to know how I can strip both the left side and right side of my strings of all whitespace except for tabs, or rather \t.

I understand I can probably loop recursively with replace, but that's messy. Theres got to be a simpler way.

Basically just removing \n, ,\r,...etc except for \t.
Cheers.

3 Answers3

3

You can also use:

s = "  \t a string example\t  "
s = s.strip(' \n\r')

This will strip any space, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.

Reference: How to trim whitespace (including tabs)?

Steven Summers
  • 5,079
  • 2
  • 20
  • 31
Sumit Murari
  • 1,597
  • 3
  • 28
  • 43
  • Lovely! Thanks for that. Didn't realise the `strip()` function took args. –  Apr 11 '17 at 05:36
0

Using re.sub:

import re

string = 'Hello\nThis is   a sample\tstring\n\r!'
print(re.sub('[ \n\r]', '', string))
hallazzang
  • 651
  • 8
  • 18
  • Short and sweet! My only issue is, is that the whitespace in the regex seems to be picking up my tabs too, and im **sure** their tabs and not converted to four whitespaces... –  Apr 11 '17 at 05:34
  • 1
    This solution will also remove spaces, \n and \r on the inside of the string, not just from the left and right side. – VMRuiz Apr 11 '17 at 07:06
0
s.strip(' ').strip('\n').strip('\r')#this will return a copy of string with '\r' and '\b' removed from left side and right side. 

See:string.strip

nick
  • 843
  • 2
  • 7
  • 17