I have a text string that starts with a number of spaces, varying between 2 & 4.
What is the simplest way to remove the leading whitespace? (ie. remove everything before a certain character?)
" Example" -> "Example"
" Example " -> "Example "
" Example" -> "Example"
This question is related to
python
string
whitespace
trim
The question doesn't address multiline strings, but here is how you would strip leading whitespace from a multiline string using python's standard library textwrap module. If we had a string like:
s = """
line 1 has 4 leading spaces
line 2 has 4 leading spaces
line 3 has 4 leading spaces
"""
if we print(s)
we would get output like:
>>> print(s)
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
and if we used textwrap.dedent
:
>>> import textwrap
>>> print(textwrap.dedent(s))
this has 4 leading spaces 1
this has 4 leading spaces 2
this has 4 leading spaces 3
To remove everything before a certain character, use a regular expression:
re.sub(r'^[^a]*', '')
to remove everything up to the first 'a'. [^a]
can be replaced with any character class you like, such as word characters.
The function strip
will remove whitespace from the beginning and end of a string.
my_str = " text "
my_str = my_str.strip()
will set my_str
to "text"
.
If you want to cut the whitespaces before and behind the word, but keep the middle ones.
You could use:
word = ' Hello World '
stripped = word.strip()
print(stripped)
Source: Stackoverflow.com