Skip to content

Commit 6ecc43d

Browse files
author
Joost Kranendonk
authored
BUG: Fix for .str.replace with repl function
.str.replace now accepts a callable (function) as replacement string. It now raises a TypeError when repl is not string like nor a callable. Docstring updated accordingly.
1 parent 018414e commit 6ecc43d

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

pandas/core/strings.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -303,8 +303,9 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
303303
----------
304304
pat : string
305305
Character sequence or regular expression
306-
repl : string
307-
Replacement sequence
306+
repl : string or function
307+
Replacement string or a function, which passed the match object and
308+
must return a replacement string to be used. See :func:`re.sub`.
308309
n : int, default -1 (all)
309310
Number of replacements to make from start
310311
case : boolean, default True
@@ -318,9 +319,9 @@ def str_replace(arr, pat, repl, n=-1, case=True, flags=0):
318319
"""
319320

320321
# Check whether repl is valid (GH 13438)
321-
if not is_string_like(repl):
322-
raise TypeError("repl must be a string")
323-
use_re = not case or len(pat) > 1 or flags
322+
if not is_string_like(repl) or not callable(repl):
323+
raise TypeError("repl must be a string or function")
324+
use_re = not case or len(pat) > 1 or flags or callable(repl)
324325

325326
if use_re:
326327
if not case:

0 commit comments

Comments
 (0)