Skip to content

For center methods, always put any extra pad character at the end of the result #137331

@hyperkai

Description

@hyperkai

Bug report

Bug description:

With str.center(), bytes.center() and bytearray.center(), ? is added to the right or left side of a string or byte string inconsistently, depending on the length of the original string or byte string as shown below so ? should be added to the left side of a string or byte string consistently not depending on the length of the original string or byte string because it's consistent and English is read from the left to the right:

print('a'.center(2, '?'))     # a?
print('ab'.center(3, '?'))    # ?ab
print('abc'.center(4, '?'))   # abc?
print('abcd'.center(5, '?'))  # ?abcd
print('abcde'.center(6, '?')) # abcde?

print(b'a'.center(2, b'?'))     # b'a?'
print(b'ab'.center(3, b'?'))    # b'?ab'
print(b'abc'.center(4, b'?'))   # b'abc?'
print(b'abcd'.center(5, b'?'))  # b'?abcd'
print(b'abcde'.center(6, b'?')) # b'abcde?'

print(bytearray(b'a').center(2, bytearray(b'?')))     # bytearray(b'a?')
print(bytearray(b'ab').center(3, bytearray(b'?')))    # bytearray(b'?ab')
print(bytearray(b'abc').center(4, bytearray(b'?')))   # bytearray(b'abc?')
print(bytearray(b'abcd').center(5, bytearray(b'?')))  # bytearray(b'?abcd')
print(bytearray(b'abcde').center(6, bytearray(b'?'))) # bytearray(b'abcde?')

In addition, with f-strings, str.format() and str.format_map(), ? is added to the right side of a string consistently not depending on the length of the original string as shown below but ? is added to the right side of a string but not the left side of a string so ? should be added to the left side of a string because English is read from the left to the right again:

print(f'{'a':?^2}')     # a?
print(f'{'ab':?^3}')    # ab?
print(f'{'abc':?^4}')   # abc?
print(f'{'abcd':?^5}')  # abcd?
print(f'{'abcde':?^6}') # abcde?

print('{:?^2}'.format('a'))     # a?
print('{:?^3}'.format('ab'))    # ab?
print('{:?^4}'.format('abc'))   # abc?
print('{:?^5}'.format('abcd'))  # abcd?
print('{:?^6}'.format('abcde')) # abcde?

print('{a:?^2}'.format_map({'a':'a'}))             # a?
print('{ab:?^3}'.format_map({'ab':'ab'}))          # ab?
print('{abc:?^4}'.format_map({'abc':'abc'}))       # abc?
print('{abcd:?^5}'.format_map({'abcd':'abcd'}))    # abcd?
print('{abcde:?^6}'.format_map({'abcde':'abcde'})) # abcde?

CPython versions tested on:

3.12

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions