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
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.
Use the str. rstrip() method to remove \r\n from a string in Python, e.g. result = my_str. rstrip() .
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With