diff --git a/doc/source/whatsnew/v2.0.3.rst b/doc/source/whatsnew/v2.0.3.rst index 3e12af946e661..8aab1e7b58f5e 100644 --- a/doc/source/whatsnew/v2.0.3.rst +++ b/doc/source/whatsnew/v2.0.3.rst @@ -14,6 +14,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed performance regression in merging on datetime-like columns (:issue:`53231`) +- Fixed regression when :meth:`DataFrame.to_string` creates extra space for string dtypes (:issue:`52690`) - For external ExtensionArray implementations, restored the default use of ``_values_for_factorize`` for hashing arrays (:issue:`53475`) - diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 6cc00ffc8889c..a9aeb5b9e0241 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1391,7 +1391,7 @@ def _format(x): fmt_values = [] for i, v in enumerate(vals): - if not is_float_type[i] and leading_space or self.formatter is not None: + if (not is_float_type[i] or self.formatter is not None) and leading_space: fmt_values.append(f" {_format(v)}") elif is_float_type[i]: fmt_values.append(float_format(v)) diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 7436644b8636a..92ced33ab338a 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -2206,6 +2206,17 @@ def test_max_rows_fitted(self, length, min_rows, max_rows, expected): result = formatter.max_rows_fitted assert result == expected + def test_no_extra_space(self): + # GH 52690: Check that no extra space is given + col1 = "TEST" + col2 = "PANDAS" + col3 = "to_string" + expected = f"{col1:<6s} {col2:<7s} {col3:<10s}" + df = DataFrame([{"col1": "TEST", "col2": "PANDAS", "col3": "to_string"}]) + d = {"col1": "{:<6s}".format, "col2": "{:<7s}".format, "col3": "{:<10s}".format} + result = df.to_string(index=False, header=False, formatters=d) + assert result == expected + def gen_series_formatting(): s1 = Series(["a"] * 100)