Skip to content

DOC: specify regex=True in str.replace #41397

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 5 commits into from
May 10, 2021
Merged
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
12 changes: 7 additions & 5 deletions pandas/core/strings/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -1231,7 +1231,7 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None):
Regex module flags, e.g. re.IGNORECASE. Cannot be set if `pat` is a compiled
regex.
regex : bool, default True
Determines if assumes the passed-in pattern is a regular expression:
Determines if the passed-in pattern is a regular expression:
- If True, assumes the passed-in pattern is a regular expression.
- If False, treats the pattern as a literal string
Expand Down Expand Up @@ -1287,7 +1287,7 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None):
To get the idea:
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f', repr)
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f', repr, regex=True)
0 <re.Match object; span=(0, 1), match='f'>oo
1 <re.Match object; span=(0, 1), match='f'>uz
2 NaN
Expand All @@ -1296,7 +1296,8 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None):
Reverse every lowercase alphabetic word:
>>> repl = lambda m: m.group(0)[::-1]
>>> pd.Series(['foo 123', 'bar baz', np.nan]).str.replace(r'[a-z]+', repl)
>>> ser = pd.Series(['foo 123', 'bar baz', np.nan])
>>> ser.str.replace(r'[a-z]+', repl, regex=True)
0 oof 123
1 rab zab
2 NaN
Expand All @@ -1306,7 +1307,8 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None):
>>> pat = r"(?P<one>\w+) (?P<two>\w+) (?P<three>\w+)"
>>> repl = lambda m: m.group('two').swapcase()
>>> pd.Series(['One Two Three', 'Foo Bar Baz']).str.replace(pat, repl)
>>> ser = pd.Series(['One Two Three', 'Foo Bar Baz'])
>>> ser.str.replace(pat, repl, regex=True)
0 tWO
1 bAR
dtype: object
Expand All @@ -1315,7 +1317,7 @@ def replace(self, pat, repl, n=-1, case=None, flags=0, regex=None):
>>> import re
>>> regex_pat = re.compile(r'FUZ', flags=re.IGNORECASE)
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace(regex_pat, 'bar')
>>> pd.Series(['foo', 'fuz', np.nan]).str.replace(regex_pat, 'bar', regex=True)
0 foo
1 bar
2 NaN
Expand Down