Text normalization
Normalize identifiers, labels, or free-form text by substituting a known pattern within a DataFrame expression.
Polars · Module
Replaces matching substrings in string expressions using a regular expression or literal pattern. By default, it changes only the first match.
Use this expression method to replace a matching substring in string values. By default, the pattern is interpreted as a regular expression and only the first match is changed; set literal=True for literal matching or increase n to replace more matches.
Expr.str.replace(pattern: str | Expr, value: str | Expr, *, literal: bool = False, n: int = 1) → Expr| Name | Type | Description |
|---|---|---|
pattern | str | Expr | Regular-expression pattern, or an expression producing one. |
value | str | Expr | Replacement string, or an expression producing one. |
literal | bool = False | Whether to interpret pattern literally instead of as a regular expression. |
n | int = 1 | Maximum number of matching occurrences to replace. |
Expr
literal=True when the search text should not be interpreted as a regular expression.n to limit how many matching occurrences are replaced per string.$1 or ${1}, with higher numbers referring to later groups.$$ when the replacement must contain a literal dollar sign.import polars as pl
df = pl.DataFrame({"text": ["123abc", "abc456"]})
result = df.with_columns(
pl.col("text").str.replace(r"abc\\b", "ABC")
)
print(result)Replaces the first substring matching the regular expression in each value.
Normalize identifiers, labels, or free-form text by substituting a known pattern within a DataFrame expression.
Extract part of a matched token and reuse it in the replacement with $1 or ${1}.
Apply a bounded number of substitutions while retaining unmatched text.
Expr.str.replace do and what are its defaults?Expr.str.replace replaces a matching regex or literal substring and returns an expression. Its defaults replace only the first match, interpret the pattern as regex, and use n=1.
Follow-up: How would you replace every match? Use Expr.str.replace_all, or pass a larger n when a bounded number of replacements is desired.
literal=False makes pattern a regular expression, while literal=True treats it as an ordinary string. The replacement value can also use capture-group references such as $1 or ${1}.
Follow-up: How can a replacement include a literal dollar sign? Escape it by doubling it as $$, or use literal matching when regex behavior is unnecessary.
The n parameter controls the number of matches to replace, and its default is 1. The method accepts either string or expression inputs for both pattern and value.
Follow-up: When should replace_all be preferred? Choose it when every non-overlapping match should be replaced without setting a replacement count.
Expr.str.replace_allSeries.str.replaceSeries.str.replace_all