Skip to content

[mypyc] Add primitives for str.ljust, rjust, center and zfill - #22412

Open
Jahongir-Qurbonov wants to merge 4 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-str-pad
Open

Jahongir-Qurbonov wants to merge 4 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-str-pad

Conversation

@Jahongir-Qurbonov

Copy link
Copy Markdown
Contributor

Add primitives for str.ljust(), str.rjust() and str.center() (with and without the fillchar argument), and str.zfill().

The implementation follows pad() and the related methods in CPython's Objects/unicodeobject.c, including:

  • the rounding used by center() for odd padding,
  • moving a leading +/- sign in zfill(),
  • returning the original object if no padding is needed and it's an exact str (a str subclass instance is converted to an exact str),
  • validating fillchar even when no padding is needed, with the same error messages.

Tests compare the results against the generic implementation (through Any) for strings and fill characters of all string kinds (ASCII, Latin-1, UCS-2, UCS-4) and a range of widths, including negative widths. Error cases and object identity are also tested.

Micro-benchmark (compiled code, 3.2M calls, best of 15, before -> after, Python 3.13):

Case Before After
s.ljust(16) 0.175s 0.089s
s.rjust(16, ".") 0.184s 0.099s
s.center(16) 0.178s 0.097s
s.zfill(8) 0.171s 0.101s
s.ljust(2) (no padding) 0.105s 0.048s
s.ljust(16) (non-ASCII) 0.180s 0.100s

Part of mypyc/mypyc#644.

@Jahongir-Qurbonov Jahongir-Qurbonov mentioned this pull request Nov 10, 2026
13 of 14 tasks
# Conflicts:
#	mypyc/doc/str_operations.rst
#	mypyc/test-data/fixtures/ir.py
# Conflicts:
#	mypyc/doc/str_operations.rst
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant