Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
in Python by (3.9k points)
How can I remove the last character of a string in a newline, In perl I used chomp function what's equivalent to that in Python?

1 Answer

0 votes
by (2k points)
edited by

There are several methods to do this I am discussing a few with you:

  • Use rstrip

 >>> 'test string\n'.rstrip()

'test string'

   To use this for newlines:

 >>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')

'test string \n \r\n\n\r '

  • You can also use lstrip() and strip() 

 >>> s = " \n\r\n \n abc def \n\r\n \n "

>>> s.strip()
'qwe   rty'
>>> s.lstrip()
'qwe   rty \n\r\n  \n  '
>>> s.rstrip()
'   \n\r\n  \n  qwe   rty'

 If you are looking for upskilling yourself in python you can join our Python Certification and learn from the industrial expert.

Related questions

0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.6k points)
+1 vote
2 answers
+3 votes
2 answers
+3 votes
2 answers

Browse Categories