Stella
Stella

Reputation: 1564

Remove \n or \t from a given 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

Upvotes: 17

Views: 77882

Answers (5)

Raymond Chenon
Raymond Chenon

Reputation: 12702

If you'd rather avoid REs. Simply replace '\t' and '\n' by the blank character ''.

def clean_string(st: str) -> str:
    #  remove \n and \t
    st = st.replace('\t', '').replace('\n', '').replace(' ', '')
    return st


if __name__ == '__main__':
    expected = clean_string("abc   \n \t \t\t \t \nefg")
    print(f"{expected}") # equals to "abcefg"

Upvotes: 0

Rukamakama
Rukamakama

Reputation: 1168

For those looking for the most Pythonic way to do it

>>> text = 'abc\n\n\t\t\t123'
>>> translator = str.maketrans({chr(10): '', chr(9): ''})
>>> text.translate(translator)
'abc123'

You can use translator to change any character in a string into another you want

Upvotes: 2

DSM
DSM

Reputation: 353369

Some more non-regex approaches, for variety:

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

Upvotes: 14

Óscar López
Óscar López

Reputation: 236114

Like this:

import re

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

Upvotes: 7

Jared
Jared

Reputation: 26407

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'

Upvotes: 26

Related Questions