Remove \ n or \ t from the given string

How can I delete a line with all \n and \t in python except using strip() ?

I want to format the string as "abc \n \t \t\t \t \nefg" to "abcefg "?

 result = re.match("\n\t ", "abc \n\t efg") print result 

and the result is None

+6
source share
3 answers

Looks like you also want to remove spaces. You can do something like this,

 >>> import re >>> s = "abc \n \t \t\t \t \nefg" >>> s = re.sub('\s+', '', s) >>> s 'abcefg' 

Another way would be to do

 >>> s = "abc \n \t \t\t \t \nefg" >>> s = s.translate(None, '\t\n ') >>> s 'abcefg' 
+10
source

A few additional non-regex approaches for a change:

 >>> s="abc \n \t \t\t \t \nefg" >>> ''.join(s.split()) 'abcefg' >>> ''.join(c for c in s if not c.isspace()) 'abcefg' 
+6
source

Like this:

 import re s = 'abc \n \t \t\t \t \nefg' re.sub(r'\s', '', s) => 'abcefg' 
+3
source

Source: https://habr.com/ru/post/949517/


All Articles