diff --git a/narwhals/expression.py b/narwhals/expression.py index 2d06c99c4..24048d45a 100644 --- a/narwhals/expression.py +++ b/narwhals/expression.py @@ -1462,7 +1462,7 @@ def ends_with(self, suffix: str) -> Expr: lambda plx: self._expr._call(plx).str.ends_with(suffix) ) - def contains(self, pattern: str, literal: bool = False) -> Expr: + def contains(self, pattern: str | Expr, literal: bool = False) -> Expr: """ Check if string contains a substring that matches a pattern. diff --git a/narwhals/series.py b/narwhals/series.py index cf7bf0d80..fa8dab6b0 100644 --- a/narwhals/series.py +++ b/narwhals/series.py @@ -1612,7 +1612,7 @@ def __init__(self, series: Series) -> None: def ends_with(self, suffix: str) -> Series: return self._series.__class__(self._series._series.str.ends_with(suffix)) - def contains(self, pattern: str, literal: bool = False) -> Series: + def contains(self, pattern: str | Expr, literal: bool = False) -> Series: return self._series.__class__( self._series._series.str.contains(pattern, literal=literal) ) diff --git a/tests/expr/str/contains_test.py b/tests/expr/str/contains_test.py new file mode 100644 index 000000000..cb14fe825 --- /dev/null +++ b/tests/expr/str/contains_test.py @@ -0,0 +1,31 @@ +from typing import Any + +import pandas as pd +import polars as pl +import pytest + +import narwhals as nw +from tests.utils import compare_dicts + +data = { + "pets": ["cat", "dog", "rabbit and parrot", "dove"] +} + +df_pandas = pd.DataFrame(data) +df_polars = pl.DataFrame(data) + +@pytest.mark.parametrize("df_any", [df_pandas, df_polars]) +def test_contains(df_any: Any) -> None: + df = nw.from_native(df_any, eager_only=True) + result = df.with_columns( + case_insensitive_match=nw.col("pets").str.contains("(?i)parrot|Dove") + ) + expected = { + "pets": ["cat", "dog", "rabbit and parrot", "dove"], + "case_insensitive_match": [False, False, True, True] + } + compare_dicts(result, expected) + result = df.with_columns( + case_insensitive_match=df["pets"].str.contains("(?i)parrot|Dove") + ) + compare_dicts(result, expected) \ No newline at end of file