Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove \n or \t from a given string

Tags:

python

string

How can I strip a string with all \n and \t in python other than using strip()?

I want to format a string like "abc \n \t \t\t \t \nefg" to "abcefg"?

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

and result is None

like image 774
Stella Avatar asked Jul 16 '13 04:07

Stella


People also ask

Does Strip () Remove \n?

The strip() method removes whitespace by default, so there is no need to call it with parameters like '\t' or '\n'. However, strings in Python are immutable and can't be modified, i.e. the line. strip() call will not change the line object. The result is a new string which is returned by the call.

How do I remove an RN from a string in Python?

Use the str. rstrip() method to remove \r\n from a string in Python, e.g. result = my_str. rstrip() .

How do I remove n characters from a string?

You can use Python's regular expressions to remove the first n characters from a string, using re's . sub() method. This is accomplished by passing in a wildcard character and limiting the substitution to a single substitution.

What is \N in Python string?

Newline character in Python: In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.


1 Answers

It 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'
like image 159
Jared Avatar answered Oct 18 '22 11:10

Jared