diff --git a/doc/source/whatsnew/v2.0.2.rst b/doc/source/whatsnew/v2.0.2.rst index 3ee7031795d16..88ec25cdd3f7f 100644 --- a/doc/source/whatsnew/v2.0.2.rst +++ b/doc/source/whatsnew/v2.0.2.rst @@ -13,7 +13,8 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- +- Fixed regression when :meth:`DataFrame.to_string` creates extra space for string dtypes (:issue:`52690`) + .. --------------------------------------------------------------------------- .. _whatsnew_202.bug_fixes: @@ -33,6 +34,7 @@ Other ~~~~~ - Raised a better error message when calling :func:`Series.dt.to_pydatetime` with :class:`ArrowDtype` with ``pyarrow.date32`` or ``pyarrow.date64`` type (:issue:`52812`) + .. --------------------------------------------------------------------------- .. _whatsnew_202.contributors: diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 24a396eb9491e..8c94af5d5b40e 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1392,7 +1392,10 @@ 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: - fmt_values.append(f" {_format(v)}") + if leading_space: + fmt_values.append(f" {_format(v)}") + else: + fmt_values.append(f"{_format(v)}") elif is_float_type[i]: fmt_values.append(float_format(v)) else: diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 175c2478808b9..6d64490d7a7b7 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -2099,6 +2099,19 @@ 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 + # Expected Output + col1 = "TEST" + col2 = "PANDAS" + col3 = "to_string" + expected = f"{col1:<6s} {col2:<7s} {col3:<10s}" + # Testing + 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)