C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Lstrip: With no argument, lstrip removes whitespace at the start of the string. The L stands for left.
Rstrip: With no argument, rstrip removes whitespace at the end. This is the right side. If no whitespace is present, nothing happens.
Tip: When a string is argument is passed to any of these strip methods, only characters in that set are removed.
Python program that uses lstrip, rstrip, strip
# Has two leading spaces and a trailing one.
value = " a line "
# Remove left spaces.
value1 = value.lstrip()
print("[" + value1 + "]")
# Remove right spaces.
value2 = value.rstrip()
print("[" + value2 + "]")
# Remove left and right spaces.
value3 = value.strip()
print("[" + value3 + "]")
Output
[a line ]
[ a line]
[a line]
Note: Strip() does not match substrings—it treats the argument as a set of characters. Here we specify all digits and some punctuation.
Tip: Lstrip and rstrip can also be used with an argument. Their behavior changes in the same way as strip.
Python program that uses strip with argument
# Has numbers on left and right, and some syntax.
value = "50342=Data,231"
# Strip all digits.
# ... Also remove equals sign and comma.
result = value.strip("0123456789=,")
print(result)
Output
Data
Lower: With lower() we can treat "cat" and "CAT" and "Cat" the same. This example is not optimally fast. But it works.
Lower, UpperPython program that uses strip, lower, dictionary
def preprocess(input):
# String and lowercase the input.
return input.strip().lower()
# Create a new dictionary.
lookup = {}
# Use preprocess to create key from string.
# ... Use key in the dictionary.
lookup[preprocess(" CAT")] = 10
# Get value from dictionary with preprocessed key.
print(lookup[preprocess("Cat ")])
Output
10
Version 1: This version calls lstrip with more chars than are needed to perform its internal logic.
Version 2: This version of the code just uses the needed characters, "012," to perform the operation.
Result: I tested and no benefit from minimizing the argument. My modifications yielded no speedups.
Python program that times lstrip
import time
# Input data.
s = "100200input"
print(s.lstrip("0123456789"))
print(s.lstrip("012"))
# Time 1.
print(time.time())
# Version 1: specify all digits.
i = 0
while i < 10000000:
result = s.lstrip("0123456789")
i += 1
# Time 2.
print(time.time())
# Version 2: specify needed digits.
i = 0
while i < 10000000:
result = s.lstrip("012")
i += 1
# Time 3.
print(time.time())
Output
input
input
1380915621.696
1380915626.524 [With all digits: 4.83 s]
1380915631.384 [With needed digits: 4.86 s]
And: These spaces are often not helpful in processing. So strip often is used before split.
Split