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.
Python code
18 linesdef 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
==============================
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
- Use the built-in `str.center(width, fill_char)` method and wrap it with banner lines: `text.center(width, fill_char)`
- 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
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.