how to use python string lstrip() with example

The lstrip() method in Python is a built-in string method that returns a copy of the string with leading characters removed. It removes any whitespace characters or specified characters from the beginning (left side) of the string.

Syntax:

string.lstrip([characters])

How to use the lstrip() method:

sentence = "   Hello, world!"
result = sentence.lstrip()
print(result)  # Output: "Hello, world!"

Example 1

Removing leading zeros from a numeric string.

number = "00001234"
result = number.lstrip("0")
print(result) # Output: "1234"

Example 2

Stripping leading prefixes from a list of strings.

prefix = "INFO_"
log_messages = ["INFO_Success", "INFO_Failure", "WARN_Critical"]
cleaned_messages = [message.lstrip(prefix) for message in log_messages]
print(cleaned_messages)

Leave a Reply

Your email address will not be published. Required fields are marked *