How to Align Text Using f-string in Python: Syntax and Examples
You can align text in Python using
f-strings by specifying alignment symbols inside curly braces: < for left, > for right, and ^ for center alignment, followed by the width. For example, f'{text:<10}' left-aligns text in a 10-character space.Syntax
The basic syntax for aligning text with f-strings is:
f'{variable:alignmentwidth}'Where:
variableis the text or value to format.alignmentis one of<(left),>(right), or^(center).widthis the total space the text should occupy.
This tells Python how to place the text inside the given width.
python
text = 'Hi' print(f'{text:<10}') # Left align print(f'{text:>10}') # Right align print(f'{text:^10}') # Center align
Output
Hi
Hi
Hi
Example
This example shows how to align different words using f-strings with specified widths and alignments.
python
words = ['apple', 'banana', 'cherry'] for word in words: print(f'Left : |{word:<10}|') print(f'Right: |{word:>10}|') print(f'Center:|{word:^10}|') print('')
Output
Left : |apple |
Right: | apple|
Center:| apple |
Left : |banana |
Right: | banana|
Center:| banana |
Left : |cherry |
Right: | cherry|
Center:| cherry |
Common Pitfalls
Common mistakes include:
- Forgetting to specify the width, which results in no visible alignment.
- Using incorrect alignment symbols or missing the colon
:. - Expecting alignment to work without a fixed width.
Always include a width number after the alignment symbol to see the effect.
python
text = 'Hello' # Wrong: no width, no alignment effect # print(f'{text:<}') # This will cause an error # Correct: print(f'{text:<10}') # Left aligned in 10 spaces
Output
Hello
Quick Reference
| Symbol | Meaning | Example |
|---|---|---|
| < | Left align | f'{text:<10}' |
| > | Right align | f'{text:>10}' |
| ^ | Center align | f'{text:^10}' |
Key Takeaways
Use
<, >, or ^ inside f-string braces to align text left, right, or center.Always specify a width number after the alignment symbol to see the alignment effect.
Without a width, alignment symbols cause errors or no visible change.
Use pipes
| in examples to clearly see spaces added by alignment.f-strings provide a simple and readable way to format aligned text in Python.