diff --git a/pandas/io/html.py b/pandas/io/html.py
index 5f38f866e1643..b8cb6679a9562 100644
--- a/pandas/io/html.py
+++ b/pandas/io/html.py
@@ -560,9 +560,7 @@ def _parse_tables(self, doc, match, attrs):
unique_tables.add(table)
if not result:
- raise ValueError(
- "No tables found matching pattern {patt!r}".format(patt=match.pattern)
- )
+ raise ValueError(f"No tables found matching pattern {repr(match.pattern)}")
return result
def _text_getter(self, obj):
@@ -618,7 +616,7 @@ def _build_xpath_expr(attrs) -> str:
if "class_" in attrs:
attrs["class"] = attrs.pop("class_")
- s = ["@{key}={val!r}".format(key=k, val=v) for k, v in attrs.items()]
+ s = [f"@{k}={repr(v)}" for k, v in attrs.items()]
return "[{expr}]".format(expr=" and ".join(s))
@@ -661,8 +659,7 @@ def _parse_tables(self, doc, match, kwargs):
# 1. check all descendants for the given pattern and only search tables
# 2. go up the tree until we find a table
- query = "//table//*[re:test(text(), {patt!r})]/ancestor::table"
- xpath_expr = query.format(patt=pattern)
+ xpath_expr = f"//table//*[re:test(text(), {repr(pattern)})]/ancestor::table"
# if any table attributes were given build an xpath expression to
# search for them
@@ -682,9 +679,7 @@ def _parse_tables(self, doc, match, kwargs):
elem.getparent().remove(elem)
if not tables:
- raise ValueError(
- "No tables found matching regex {patt!r}".format(patt=pattern)
- )
+ raise ValueError(f"No tables found matching regex {repr(pattern)}")
return tables
def _equals_tag(self, obj, tag):
@@ -833,8 +828,7 @@ def _parser_dispatch(flavor):
valid_parsers = list(_valid_parsers.keys())
if flavor not in valid_parsers:
raise ValueError(
- "{invalid!r} is not a valid flavor, valid flavors "
- "are {valid}".format(invalid=flavor, valid=valid_parsers)
+ f"{repr(flavor)} is not a valid flavor, valid flavors are {valid_parsers}"
)
if flavor in ("bs4", "html5lib"):
@@ -863,13 +857,13 @@ def _validate_flavor(flavor):
elif isinstance(flavor, abc.Iterable):
if not all(isinstance(flav, str) for flav in flavor):
raise TypeError(
- "Object of type {typ!r} is not an iterable of "
- "strings".format(typ=type(flavor).__name__)
+ f"Object of type {repr(type(flavor).__name__)} "
+ f"is not an iterable of strings"
)
else:
- fmt = "{flavor!r}" if isinstance(flavor, str) else "{flavor}"
- fmt += " is not a valid flavor"
- raise ValueError(fmt.format(flavor=flavor))
+ msg = repr(flavor) if isinstance(flavor, str) else str(flavor)
+ msg += " is not a valid flavor"
+ raise ValueError(msg)
flavor = tuple(flavor)
valid_flavors = set(_valid_parsers)
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py
index bbec148b8745d..7403e6d254d03 100755
--- a/pandas/io/parsers.py
+++ b/pandas/io/parsers.py
@@ -972,10 +972,10 @@ def _clean_options(self, options, engine):
elif engine not in ("python", "python-fwf"):
# wait until regex engine integrated
fallback_reason = (
- "the 'c' engine does not support"
- " regex separators (separators > 1 char and"
- r" different from '\s+' are"
- " interpreted as regex)"
+ "the 'c' engine does not support "
+ "regex separators (separators > 1 char and "
+ r"different from '\s+' are "
+ "interpreted as regex)"
)
engine = "python"
elif delim_whitespace:
@@ -990,9 +990,9 @@ def _clean_options(self, options, engine):
encodeable = False
if not encodeable and engine not in ("python", "python-fwf"):
fallback_reason = (
- "the separator encoded in {encoding}"
- " is > 1 char long, and the 'c' engine"
- " does not support such separators".format(encoding=encoding)
+ "the separator encoded in {encoding} "
+ "is > 1 char long, and the 'c' engine "
+ "does not support such separators".format(encoding=encoding)
)
engine = "python"
@@ -1021,21 +1021,19 @@ def _clean_options(self, options, engine):
if "python" in engine:
for arg in _python_unsupported:
if fallback_reason and result[arg] != _c_parser_defaults[arg]:
- msg = (
- "Falling back to the 'python' engine because"
- " {reason}, but this causes {option!r} to be"
- " ignored as it is not supported by the 'python'"
- " engine."
- ).format(reason=fallback_reason, option=arg)
- raise ValueError(msg)
+ raise ValueError(
+ f"Falling back to the 'python' engine because "
+ f"{fallback_reason}, but this causes {repr(arg)} to be "
+ f"ignored as it is not supported by the 'python' engine."
+ )
del result[arg]
if fallback_reason:
warnings.warn(
(
- "Falling back to the 'python' engine because"
- " {0}; you can avoid this warning by specifying"
- " engine='python'."
+ "Falling back to the 'python' engine because "
+ "{0}; you can avoid this warning by specifying "
+ "engine='python'."
).format(fallback_reason),
ParserWarning,
stacklevel=5,
@@ -1056,8 +1054,8 @@ def _clean_options(self, options, engine):
depr_default = _deprecated_defaults[arg]
msg = (
- "The '{arg}' argument has been deprecated "
- "and will be removed in a future version.".format(arg=arg)
+ f"The {repr(arg)} argument has been deprecated and will be "
+ f"removed in a future version."
)
if result.get(arg, depr_default) != depr_default:
@@ -1081,9 +1079,8 @@ def _clean_options(self, options, engine):
if converters is not None:
if not isinstance(converters, dict):
raise TypeError(
- "Type converters must be a dict or"
- " subclass, input was "
- "a {0!r}".format(type(converters).__name__)
+ f"Type converters must be a dict or subclass, "
+ f"input was a {repr(type(converters).__name__)}"
)
else:
converters = {}
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py
index beb276478070e..375e6fe2b02c7 100644
--- a/pandas/plotting/_core.py
+++ b/pandas/plotting/_core.py
@@ -743,7 +743,7 @@ def _get_call_args(backend_name, data, args, kwargs):
if args and isinstance(data, ABCSeries):
positional_args = str(args)[1:-1]
keyword_args = ", ".join(
- f"{name}={value!r}" for (name, default), value in zip(arg_def, args)
+ f"{name}={repr(value)}" for (name, default), value in zip(arg_def, args)
)
msg = (
"`Series.plot()` should not be called with positional "
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py
index 1146b486a3eb4..2208fbf933387 100644
--- a/pandas/tests/computation/test_eval.py
+++ b/pandas/tests/computation/test_eval.py
@@ -1114,11 +1114,11 @@ def test_performance_warning_for_poor_alignment(self, engine, parser):
if not is_python_engine:
assert len(w) == 1
msg = str(w[0].message)
+ loged = np.log10(s.size - df.shape[1])
expected = (
- "Alignment difference on axis {0} is larger"
- " than an order of magnitude on term {1!r}, "
- "by more than {2:.4g}; performance may suffer"
- "".format(1, "df", np.log10(s.size - df.shape[1]))
+ f"Alignment difference on axis 1 is larger "
+ f"than an order of magnitude on term 'df', "
+ f"by more than {loged:.4g}; performance may suffer"
)
assert msg == expected
diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py
index 6206b333d29e1..b52f24f9e06f1 100644
--- a/pandas/tests/frame/test_alter_axes.py
+++ b/pandas/tests/frame/test_alter_axes.py
@@ -342,7 +342,7 @@ def __init__(self, name, color):
self.color = color
def __str__(self) -> str:
- return "".format(self=self)
+ return f""
# necessary for pretty KeyError
__repr__ = __str__
@@ -419,7 +419,7 @@ def __init__(self, name, color):
self.color = color
def __str__(self) -> str:
- return "".format(self=self)
+ return f""
thing1 = Thing("One", "red")
thing2 = Thing("Two", "blue")
diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py
index cd1bee356ed8e..abd8ef98ff871 100644
--- a/pandas/tests/frame/test_query_eval.py
+++ b/pandas/tests/frame/test_query_eval.py
@@ -27,7 +27,7 @@ def engine(request):
def skip_if_no_pandas_parser(parser):
if parser != "pandas":
- pytest.skip("cannot evaluate with parser {0!r}".format(parser))
+ pytest.skip(f"cannot evaluate with parser {repr(parser)}")
class TestCompat:
diff --git a/pandas/tests/indexes/timedeltas/test_timedelta.py b/pandas/tests/indexes/timedeltas/test_timedelta.py
index ba0af7dd8136c..d59b6c18f6042 100644
--- a/pandas/tests/indexes/timedeltas/test_timedelta.py
+++ b/pandas/tests/indexes/timedeltas/test_timedelta.py
@@ -234,7 +234,7 @@ def test_pickle(self):
def test_hash_error(self):
index = timedelta_range("1 days", periods=10)
with pytest.raises(
- TypeError, match=("unhashable type: {0.__name__!r}".format(type(index)))
+ TypeError, match=(f"unhashable type: {repr(type(index).__name__)}")
):
hash(index)
diff --git a/pandas/tests/io/parser/test_unsupported.py b/pandas/tests/io/parser/test_unsupported.py
index b23ddf5bd9292..07ab41b47bf27 100644
--- a/pandas/tests/io/parser/test_unsupported.py
+++ b/pandas/tests/io/parser/test_unsupported.py
@@ -96,9 +96,9 @@ def test_python_engine(self, python_engine):
for default in py_unsupported:
msg = (
- "The {default!r} option is not supported with the {python_engine!r}"
- " engine"
- ).format(default=default, python_engine=python_engine)
+ f"The {repr(default)} option is not "
+ f"supported with the {repr(python_engine)} engine"
+ )
kwargs = {default: object()}
with pytest.raises(ValueError, match=msg):
diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py
index d8d617ceeebff..353946a311c1a 100644
--- a/pandas/tests/io/test_html.py
+++ b/pandas/tests/io/test_html.py
@@ -902,8 +902,8 @@ def test_computer_sales_page(self, datapath):
def test_wikipedia_states_table(self, datapath):
data = datapath("io", "data", "html", "wikipedia_states.html")
- assert os.path.isfile(data), "{data!r} is not a file".format(data=data)
- assert os.path.getsize(data), "{data!r} is an empty file".format(data=data)
+ assert os.path.isfile(data), f"{repr(data)} is not a file"
+ assert os.path.getsize(data), f"{repr(data)} is an empty file"
result = self.read_html(data, "Arizona", header=1)[0]
assert result["sq mi"].dtype == np.dtype("float64")
diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py
index 3c97b75ecfa0c..0e2f8ee6543e1 100644
--- a/pandas/tests/test_strings.py
+++ b/pandas/tests/test_strings.py
@@ -296,10 +296,8 @@ def test_api_per_method(
else:
# GH 23011, GH 23163
msg = (
- "Cannot use .str.{name} with values of inferred dtype "
- "{inferred_dtype!r}.".format(
- name=method_name, inferred_dtype=inferred_dtype
- )
+ f"Cannot use .str.{method_name} with values of "
+ f"inferred dtype {repr(inferred_dtype)}."
)
with pytest.raises(TypeError, match=msg):
method(*args, **kwargs)