Skip to content

Commit bf2f6e5

Browse files
authored
BUG: Error reporting str.startswith and str.endswith (#45897)
* BUG: Error reporting str.startswith and str.endswith Close #3485 * Bug: Explicit TypeError parameter in whatsnew
1 parent f5b5b19 commit bf2f6e5

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

doc/source/whatsnew/v1.5.0.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,7 @@ Conversion
304304

305305
Strings
306306
^^^^^^^
307-
-
307+
- Bug in :meth:`str.startswith` and :meth:`str.endswith` when using other series as parameter _pat_. Now raises ``TypeError`` (:issue:`3485`)
308308
-
309309

310310
Interval

pandas/core/strings/accessor.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2282,6 +2282,9 @@ def startswith(self, pat, na=None):
22822282
3 False
22832283
dtype: bool
22842284
"""
2285+
if not isinstance(pat, str):
2286+
msg = f"expected a string object, not {type(pat).__name__}"
2287+
raise TypeError(msg)
22852288
result = self._data.array._str_startswith(pat, na=na)
22862289
return self._wrap_result(result, returns_string=False)
22872290

@@ -2339,6 +2342,9 @@ def endswith(self, pat, na=None):
23392342
3 False
23402343
dtype: bool
23412344
"""
2345+
if not isinstance(pat, str):
2346+
msg = f"expected a string object, not {type(pat).__name__}"
2347+
raise TypeError(msg)
23422348
result = self._data.array._str_endswith(pat, na=na)
23432349
return self._wrap_result(result, returns_string=False)
23442350

pandas/tests/strings/test_strings.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,17 @@
1616
import pandas._testing as tm
1717

1818

19+
@pytest.mark.parametrize("pattern", [0, True, Series(["foo", "bar"])])
20+
def test_startswith_endswith_non_str_patterns(pattern):
21+
# GH3485
22+
ser = Series(["foo", "bar"])
23+
msg = f"expected a string object, not {type(pattern).__name__}"
24+
with pytest.raises(TypeError, match=msg):
25+
ser.str.startswith(pattern)
26+
with pytest.raises(TypeError, match=msg):
27+
ser.str.endswith(pattern)
28+
29+
1930
def assert_series_or_index_equal(left, right):
2031
if isinstance(left, Series):
2132
tm.assert_series_equal(left, right)

0 commit comments

Comments
 (0)