Skip to content

Commit d5c3f1b

Browse files
committed
BUG: Fix for .str.replace with invalid input
.str.replace now raises TypeError when replacement string is not string like
1 parent d814f43 commit d5c3f1b

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

doc/source/whatsnew/v0.18.2.txt

+1
Original file line numberDiff line numberDiff line change
@@ -424,3 +424,4 @@ Bug Fixes
424424

425425

426426
- Bug in ``Categorical.remove_unused_categories()`` changes ``.codes`` dtype to platform int (:issue:`13261`)
427+
- Bug in ``.str.replace`` does not raise TypeError for invalid replacement (:issue:`13438`)

pandas/core/strings.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from pandas.core.common import (isnull, notnull, _values_from_object,
55
is_bool_dtype,
66
is_list_like, is_categorical_dtype,
7-
is_object_dtype)
7+
is_object_dtype, is_string_like)
88
from pandas.core.algorithms import take_1d
99
import pandas.compat as compat
1010
from pandas.core.base import AccessorProperty, NoNewAttributesMixin
@@ -309,6 +309,8 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
309309
-------
310310
replaced : Series/Index of objects
311311
"""
312+
if not is_string_like(repl): # Check whether repl is valid (GH 13438)
313+
raise TypeError("repl must be a string")
312314
use_re = not case or len(pat) > 1 or flags
313315

314316
if use_re:

pandas/tests/test_strings.py

+7
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,13 @@ def test_replace(self):
430430
result = values.str.replace("(?<=\w),(?=\w)", ", ", flags=re.UNICODE)
431431
tm.assert_series_equal(result, exp)
432432

433+
# GH 13438
434+
for pdClass in (Series, Index):
435+
for repl in (None, 3, {'a': 'b'}):
436+
for data in (['a', 'b', None], ['a', 'b', 'c', 'ad']):
437+
values = pdClass(data)
438+
self.assertRaises(TypeError, values.str.replace, 'a', repl)
439+
433440
def test_repeat(self):
434441
values = Series(['a', 'b', NA, 'c', NA, 'd'])
435442

0 commit comments

Comments
 (0)