How to Center Text in a Fixed-Width Banner in Python

Centers any text inside a fixed-width banner using fill characters and computed padding.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

18 lines
Python 3.9+
def center_text_banner(text, width=40, fill_char="="):
    """Center text within a fixed-width banner."""
    if len(text) >= width:
        return text
    
    total_padding = width - len(text)
    left_padding = total_padding // 2
    right_padding = total_padding - left_padding
    
    banner_line = fill_char * width
    centered_line = fill_char * left_padding + text + fill_char * right_padding
    
    return f"{banner_line}\n{centered_line}\n{banner_line}"

if __name__ == "__main__":
    print(center_text_banner("Hello World", width=30))
    print()
    print(center_text_banner("Python", width=20, fill_char="-"))

Output

stdout
==============================
          Hello World          
==============================

--------------------
       Python       
--------------------

How it works

The center_text_banner function first checks if the text is longer than or equal to the desired width; if so, it returns the text unchanged to avoid negative padding. Otherwise, it calculates total padding as width - len(text) and splits it nearly equally into left and right padding (the left gets the floor of half, the right gets the remainder). The fill_char is used to create a banner line of the full width, and a centered line is built by joining the left padding, the text, and the right padding. Finally, the function returns the three-line banner: a top line, the centered text line, and a bottom line.

Common mistakes

  • Not handling the case where text exceeds the banner width, leading to negative padding
  • Mixing up `//` floor division with regular division, producing fractional padding
  • Using `fill_char` inconsistently between the banner lines and the centered line

Variations

  1. Use the built-in `str.center(width, fill_char)` method and wrap it with banner lines: `text.center(width, fill_char)`
  2. Output the banner as a single string without newlines between lines by joining with `'\n'.join(...)`

Real-world use cases

  • Formatting command-line tool output with section headers that are easy to scan in logs.
  • Creating visually separated announcements or alerts in terminal-based scripts and dashboards.
  • Generating readable separators in generated reports or text-based configuration previews.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.