Skip to content

pandas/str-replace-regex-default

Rule str-replace-regex-default
Pack pandas
Severity error
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

Since pandas 2.0, str.replace reads its pattern as plain text, so a regular expression replaces nothing. Pass regex=True.

digits = df["phone"].str.replace(r"\D", "")
digits = df["phone"].str.replace(r"\D", "", regex=True)

The rule reports df["s"].str.replace(r"\d+", ""), which replaces nothing, because str.replace reads its pattern as plain text since pandas 2.0. The rule reports only a pattern that can't be meant as plain text, as the table shows.

Pattern Reported
a class such as \d, a set in brackets, .* or .+, a ^ at the start, or two choices joined by a pipe yes
".", "$" and "(" no

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes regex=True.

The fix is unsafe, because the code can mean a set in brackets as plain text.

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

str.replace reads the pattern as plain text since pandas 2.0, so this regular expression matches nothing. Pass regex=True.

Browse the other rules of the pandas pack.