How do I remove leading whitespace in Python?
The lstrip()
method will remove leading whitespaces, newline and tab characters on a string beginning:
>>> ' hello world!'.lstrip()
'hello world!'
Edit
As balpha pointed out in the comments, in order to remove only spaces from the beginning of the string, lstrip(' ')
should be used:
>>> ' hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'
Related question:
- Trimming a string in Python
How to remove leading and trailing spaces from a string?
You can use the strip()
method to remove trailing and leading spaces:
>>> s = ' abd cde '
>>> s.strip()
'abd cde'
Note: the internal spaces are preserved.
Remove white spaces from the beginning of each string in a list
Use str.lstrip in a list comprehension:
my_list = [' a', ' b', ' c']
my_list = [i.lstrip() for i in my_list]
print(my_list) # ['a', 'b', 'c']
Remove all whitespace in a string
If you want to remove leading and ending spaces, use str.strip()
:
>>> " hello apple ".strip()
'hello apple'
If you want to remove all space characters, use str.replace()
(NB this only removes the “normal” ASCII space character ' ' U+0020
but not any other whitespace):
>>> " hello apple ".replace(" ", "")
'helloapple'
If you want to remove duplicated spaces, use str.split()
followed by str.join()
:
>>> " ".join(" hello apple ".split())
'hello apple'
Regular Expression - Python - Remove Leading Whitespace
You could use strip()
to remove leading and trailing whitespaces:
In [1]: ' 56.00 '.strip()
Out[1]: '56.00'
How to remove leading and trailing whitespace from each line in an MD file while preserving empty lines?
You could split on the line break character - '\n'
and rejoin all the entries with the leading and trailing spaces stripped -
print(repr(markdown))
#' ## This is a headline\n\n [1] This is the first paragraph\n \n [2] This is the second paragraph\n \n \n a. This is the third paragraph; \n b. This is the fourth paragraph.'
clean_markdown = '\n'.join(_.strip() for _ in markdown.split('\n'))
print(repr(clean_markdown))
#'## This is a headline\n\n[1] This is the first paragraph\n\n[2] This is the second paragraph\n\n\na. This is the third paragraph;\nb. This is the fourth paragraph.'
And write this clean_markdown
to your file
How do I trim whitespace?
For whitespace on both sides, use str.strip
:
s = " \t a string example\t "
s = s.strip()
For whitespace on the right side, use str.rstrip
:
s = s.rstrip()
For whitespace on the left side, use str.lstrip
:
s = s.lstrip()
You can provide an argument to strip arbitrary characters to any of these functions, like this:
s = s.strip(' \t\n\r')
This will strip any space, \t
, \n
, or \r
characters from both sides of the string.
The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub
:
import re
print(re.sub('[\s+]', '', s))
That should print out:
astringexample
How do I remove trailing and leading white space from items in a list in Python?
You can use the .strip
function in python. Using it in list comprehension.
my_list = [x.strip() for x in my_list]
Hope this helps.
Related Topics
Child Processes Created with Python Multiprocessing Module Won't Print
How to Normalize JSON Correctly by Python Pandas
Is There a Difference Between Continue and Pass in a for Loop in Python
Concat Dataframe Reindexing Only Valid with Uniquely Valued Index Objects
Matplotlib: Draw Grid Lines Behind Other Graph Elements
How to Use Boto to Stream a File Out of Amazon S3 to Rackspace Cloudfiles
Good or Bad Practice in Python: Import in the Middle of a File
Best Way to Parse a Url Query String
How to Force a Python Wheel to Be Platform Specific When Building It
How to Crop to Largest Interior Bounding Box in Opencv
What Is the Purpose of Subclassing the Class "Object" in Python
How to Read Datetime Back from SQLite as a Datetime Instead of String in Python
How to Convert a Scikit-Learn Dataset to a Pandas Dataset
Pandas: Change Data Type of Series to String
"Private" (Implementation) Class in Python