Skip to content

BUG: Error reporting str.startswith and str.endswith #45897

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 14, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v1.5.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions pandas/core/strings/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/strings/test_strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down