formatting
str.lstrip
Returns a copy of the string with leading characters removed. Defaults to whitespace; a chars argument specifies a set of characters to strip from the left.
str.lstrip([chars]) Parameters
| Parameter | Purpose |
|---|---|
| chars | character set to strip from the left; default is whitespace |
| returns | new str trimmed on the left (original unchanged — str is immutable) |
Examples
>>> ' hello '.lstrip()
'hello ' only leading whitespace is removed
>>> '000123'.lstrip('0')
'123' chars set removes any of those characters from the left
>>> 'www.example.com'.lstrip('cmowz.')
'example.com' removes any leading char in the set (a common gotcha)
>>> '\n\tspace'.lstrip()
'space' tabs and newlines count
Gotcha
chars is a set of characters, not a prefix. Since 3.9 use str.removeprefix() to strip a literal prefix string.
Related methods
str.strip
Returns a copy of the string with leading and trailing whitespace removed. If chars is given, removes any leading/trailing characters that appear in the chars set (not a prefix/suffix — it is a character set).
str.rstrip
Returns a copy of the string with trailing characters removed. Defaults to whitespace; a chars argument specifies a set of characters to strip from the right.
str.startswith
Returns True if the string starts with the given prefix, otherwise False. prefix may also be a tuple of strings to test against multiple candidates.
str.format
Substitutes replacement fields delimited by { } in the string with values from args and kwargs, using the Format Specification Mini-Language. In modern Python, f-strings are usually preferred for literals; str.format() remains ideal for templates loaded at runtime.
str.rjust
Returns the string right-justified in a field of the given width, padded on the left with fillchar. Returns the original string unchanged if it is already at least width characters long.