String Cleaning
Strip Whitespace
Remove leading and trailing whitespace from each string in a column. By
hand, call s.strip() on each element in a loop. With pandas,
Series.str.strip() applies the same operation across the entire column
at once.
By hand
With pandas
df['x'].str.strip() returns a new Series with every string stripped.
The dtype stays object (strings). The snapshot shows the cleaned values
alongside the original dtype.
naive.py
strings = [' Alice ', 'Bob ', ' Carol', 'Dave', ' Eve ']
result = []
for s in strings:
result.append(s.strip())
print('RESULT:', result)
library.py
import pandas as pd
from dalib.display import set_display
set_display()
strings = [' Alice ', 'Bob ', ' Carol', 'Dave', ' Eve ']
df = pd.DataFrame({'x': strings})
s = df['x'].str.strip()
result = s.tolist()
print('index:', s.index.tolist())
print('dtype:', s.dtype)
print('values:', s.tolist())
print('RESULT:', result)
index: [0, 1, 2, 3, 4]
dtype: object
values: ['Alice', 'Bob', 'Carol', 'Dave', 'Eve']
RESULT: ['Alice', 'Bob', 'Carol', 'Dave', 'Eve']
Implementation notes
str.strip()removes all leading and trailing whitespace characters (spaces, tabs, newlines). Usestr.lstrip()to strip only the left side, orstr.rstrip()for only the right.- Pass a character string to strip specific characters instead of
whitespace:
s.strip('.')removes leading/trailing dots. - Whitespace inside the string is unaffected — use
str.replaceor regex to collapse internal spaces. - Cross-reference:
normalize-case(this chapter) — strip and lowercase are often applied together as the first cleaning step.