diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index ea5258cf1537d..ac1565d1e11c3 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -304,7 +304,7 @@ Conversion Strings ^^^^^^^ -- +- Bug in :meth:`str.startswith` and :meth:`str.endswith` when using other series as parameter _pat_. Now raises ``TypeError`` (:issue:`3485`) - Interval diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 6a0fa3c311288..b7ccc087ff1f1 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -2282,6 +2282,9 @@ def startswith(self, pat, na=None): 3 False dtype: bool """ + if not isinstance(pat, str): + msg = f"expected a string object, not {type(pat).__name__}" + raise TypeError(msg) result = self._data.array._str_startswith(pat, na=na) return self._wrap_result(result, returns_string=False) @@ -2339,6 +2342,9 @@ def endswith(self, pat, na=None): 3 False dtype: bool """ + if not isinstance(pat, str): + msg = f"expected a string object, not {type(pat).__name__}" + raise TypeError(msg) result = self._data.array._str_endswith(pat, na=na) return self._wrap_result(result, returns_string=False) diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py index 9a82110f65f83..b061ef0bd8a15 100644 --- a/pandas/tests/strings/test_strings.py +++ b/pandas/tests/strings/test_strings.py @@ -16,6 +16,17 @@ import pandas._testing as tm +@pytest.mark.parametrize("pattern", [0, True, Series(["foo", "bar"])]) +def test_startswith_endswith_non_str_patterns(pattern): + # GH3485 + ser = Series(["foo", "bar"]) + msg = f"expected a string object, not {type(pattern).__name__}" + with pytest.raises(TypeError, match=msg): + ser.str.startswith(pattern) + with pytest.raises(TypeError, match=msg): + ser.str.endswith(pattern) + + def assert_series_or_index_equal(left, right): if isinstance(left, Series): tm.assert_series_equal(left, right)