Skip to content

Commit

Permalink
Backport PR #53855: BUG: Fix string formatting (#53860)
Browse files Browse the repository at this point in the history
* Backport PR #53855: BUG: Fix string formatting

* Remove note

---------

Co-authored-by: Xiao Yuan <yuanx749@gmail.com>
  • Loading branch information
mroeschke and yuanx749 authored Jun 26, 2023
1 parent 000a42f commit 7d8be44
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
1 change: 1 addition & 0 deletions doc/source/whatsnew/v2.0.3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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`)
-

.. ---------------------------------------------------------------------------
Expand Down
2 changes: 1 addition & 1 deletion pandas/io/formats/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -1426,7 +1426,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))
Expand Down
11 changes: 11 additions & 0 deletions pandas/tests/io/formats/test_format.py
Original file line number Diff line number Diff line change
Expand Up @@ -2165,6 +2165,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)
Expand Down

0 comments on commit 7d8be44

Please sign in to comment.