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
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
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)