Try the method rstrip()
(see doc Python 2 and Python 3)
>>> 'test string\n'.rstrip() 'test string'
Python’s rstrip()
method strips all kinds of trailing whitespace by default, not just one newline as Perl does with chomp
.
>>> 'test string \n \r\n\n\r \n\n'.rstrip() 'test string'
To strip only newlines:
>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n') 'test string \n \r\n\n\r '
In addition to rstrip()
, there are also the methods strip()
and lstrip()
. Here is an example with the three of them:
>>> s = " \n\r\n \n abc def \n\r\n \n " >>> s.strip() 'abc def' >>> s.lstrip() 'abc def \n\r\n \n ' >>> s.rstrip() ' \n\r\n \n abc def'
Related Posts:
- How can I remove a trailing newline?
- How can I remove a trailing newline?
- Writing a list to a file with Python
- Writing a list to a file with Python
- How to remove \n from a list element?
- Writing string to a file on a new line every time
- Writing string to a file on a new line every time
- Print empty line?
- How do I lowercase a string in Python?
- Difference between del, remove, and pop on lists
- How to use the pass statement
- How do you round UP a number?
- How do I update\upgrade pip itself from inside my virtual environment?
- ImportError: DLL load failed: The specified module could not be found
- Replacements for switch statement in Python?
- Correct way to write line to file?
- How to read a file line-by-line into a list?
- How do I sort a dictionary by value?
- What does %s mean in a python format string?
- Redirecting to URL in Flask
- TypeError: ‘float’ object is not callable
- Plotting a 2D heatmap with Matplotlib
- Purpose of __repr__ method?
- json.dumps vs flask.jsonify
- How to print like printf in Python3?
- “Defaulting to user installation because normal site-packages is not writeable” python message
- How to install pytorch in Anaconda with conda or pip?
- How can I remove a key from a Python dictionary?
- What does numpy.random.seed(0) do?
- How do I check if a variable exists?
- Is there a label/goto in Python?
- Why do I get “Pickle – EOFError: Ran out of input” reading an empty file?
- Getting TypeError: __init__() missing 1 required positional argument: ‘on_delete’ when trying to add parent table after child table with entries
- Python Pandas Counting the Occurrences of a Specific value
- What does the c underscore expression `c_` do exactly?
- Count unique values per groups with Pandas
- Get unique values from a list in python [duplicate]
- What is the problem with shadowing names defined in outer scopes?
- TypeError: write() argument must be str, not bytes (Python 3 vs Python 2 )
- How to clear the interpreter console?
- How to make a class JSON serializable
- What does the ‘b’ character do in front of a string literal?
- How can I upgrade NumPy?
- How to get element-wise matrix multiplication (Hadamard product) in numpy?
- Matplotlib automatic legend outside plot
- Why am I getting this syntax error: keyword can’t be an expression
- Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
- What is dtype(‘O’), in pandas?
- ctypes – Beginner
- Keras, how do I predict after I trained a model?
- How do I find out my PYTHONPATH using Python?
- ValueError: could not broadcast input array from shape (224,224,3) into shape (224,224)
- Flask ImportError: No Module Named Flask
- ModuleNotFoundError: No module named ‘MySQLdb’
- How to change dataframe column names in pyspark?
- Normalize data in pandas
- Can’t broadcast input array from shape (3,1) into shape (3,)
- How to create an array of bits in Python?
- Setting Django up to use MySQL
- In Python, when to use a Dictionary, List or Set?
- How can I check for NaN values?
- Python – how to use the constant e^
- TypeError : Unhashable type
- Read PDF in Python and convert to text in PDF
- Importing variables from another file in Python
- How to read a file without newlines?
- Encrypt & Decrypt using PyCrypto AES 256
- Is there a list of Pytz Timezones?
- Flask example with POST
- How do I change the figure size with subplots?
- Clear terminal in Python [duplicate]
- can’t open tensorboard 0.0.0.0:6006 or localhost:6006
- ImportError: No module named six
- Easy pretty printing of floats?
- Algorithm for solving Sudoku
- How to read pickle file?
- How to set timeout on python’s socket recv method?
- How does str(list) work?
- Automatic indentation for Python in Notepad++
- pandas groupby sort within groups
- Python Socket Receive Large Amount of Data
- What should I use to open a url instead of urlopen in urllib3
- How to find out whether a file is at its `eof`?
- TypeError: Image data can not convert to float
- coercing to Unicode: need string or buffer, NoneType found when rendering in django admin
- Convert from ASCII string encoded in Hex to plain ASCII?
- Simple way to create matrix of random numbers
- pandas: multiple conditions while indexing data frame – unexpected behavior
- ‘instancemethod’ object has no attribute ‘__getitem__’ with class variables
- Symbol not found: __PyCodecInfo_GetIncrementalDecoder
- How can I tail a log file in Python?
- How to write unicode strings into a file?
- python-How to set global variables in Flask?
- How do I install pip on macOS or OS X?
- NameError: name ‘get_ipython’ is not defined
- Equivalent to matlab’s imagesc in matplotlib? [duplicate]
- bash: syntax error near unexpected token `(‘ – Python
- Find all files in a directory with extension .txt in Python
- “public” or “private” attribute in Python ? What is the best way?
- How to search for a string in text files?