polars.Expr.str.replace#

Expr.str.replace(pattern: str | Expr, value: str | Expr, literal: bool = False) Expr[source]#

Replace first matching regex/literal substring with a new string value.

Parameters:
pattern

Regex pattern.

value

Replacement string.

literal

Treat pattern as a literal string.

See also

replace_all

Replace all matching regex/literal substrings.

Examples

>>> df = pl.DataFrame({"id": [1, 2], "text": ["123abc", "abc456"]})
>>> df.with_column(
...     pl.col("text").str.replace(r"abc\b", "ABC")
... )  
shape: (2, 2)
┌─────┬────────┐
│ id  ┆ text   │
│ --- ┆ ---    │
│ i64 ┆ str    │
╞═════╪════════╡
│ 1   ┆ 123ABC │
├╌╌╌╌╌┼╌╌╌╌╌╌╌╌┤
│ 2   ┆ abc456 │
└─────┴────────┘