Skip to content

daft.functions.replace#

replace #

replace(expr: Expression, search: str | Expression, replacement: str | Expression) -> Expression

Replaces all occurrences of a substring in a string with a replacement string.

Parameters:

Name Type Description Default
expr Expression

The string expression to be replaced

required
search str | Expression

The substring to replace

required
replacement str | Expression

The replacement string

required

Returns:

Name Type Description
Expression Expression

a String expression with patterns replaced by the replacement string

Examples:

1
2
3
4
5
>>> import daft
>>> from daft.functions import replace
>>>
>>> df = daft.from_pydict({"data": ["foo", "bar", "baz"]})
>>> df.with_column("replace", replace(df["data"], "ba", "123")).collect()
╭────────┬─────────╮
│ data   ┆ replace │
│ ---    ┆ ---     │
│ String ┆ String  │
╞════════╪═════════╡
│ foo    ┆ foo     │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ bar    ┆ 123r    │
├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
│ baz    ┆ 123z    │
╰────────┴─────────╯
(Showing first 3 of 3 rows)
Source code in daft/functions/str.py
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
def replace(
    expr: Expression,
    search: str | Expression,
    replacement: str | Expression,
) -> Expression:
    """Replaces all occurrences of a substring in a string with a replacement string.

    Args:
        expr: The string expression to be replaced
        search: The substring to replace
        replacement: The replacement string

    Returns:
        Expression: a String expression with patterns replaced by the replacement string

    Examples:
        >>> import daft
        >>> from daft.functions import replace
        >>>
        >>> df = daft.from_pydict({"data": ["foo", "bar", "baz"]})
        >>> df.with_column("replace", replace(df["data"], "ba", "123")).collect()
        ╭────────┬─────────╮
        │ data   ┆ replace │
        │ ---    ┆ ---     │
        │ String ┆ String  │
        ╞════════╪═════════╡
        │ foo    ┆ foo     │
        ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
        │ bar    ┆ 123r    │
        ├╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌┤
        │ baz    ┆ 123z    │
        ╰────────┴─────────╯
        <BLANKLINE>
        (Showing first 3 of 3 rows)

    """
    return Expression._call_builtin_scalar_fn("replace", expr, search, replacement)