How to format a string using fixed-width fields in Python

4 Answers

0 votes
'''
Common format specifiers
-----------------------------------
f"{text:<10}" # Left-align string, width 10
f"{text:>10}" # Right-align string, width 10
f"{number:5d}" # Integer, width 5
f"{number:08d}" # Integer, width 8, padded with zeros
f"{value:12.2f}" # Float, width 12, 2 decimal places
'''

def format_record(name, age, salary):
    """
    Format a record using fixed-width fields.

    <15   = left-align text in a field 15 characters wide
    >10   = right-align integer in a field 10 characters wide
    >12.2f = right-align float in a field 12 characters wide
             with 2 digits after the decimal point
    """

    return f"{name:<15}{age:>10}{salary:>12.2f}"


# Store the formatted string in a variable
result = format_record("Darth ", 53, 89000.0)

print(result)


'''
run:

Darth                  53    89000.00

'''

 



answered Oct 18 by avibootz
0 votes
# Left-align "Hello" in a field 10 characters wide
result = f"{'Hello':<10}"

print(f"|{result}|")


'''
run:

|Hello     |

'''

 



answered Oct 18 by avibootz
0 votes
number = 123

# Pad with leading zeros to width 8
result = f"{number:08d}"

print(result)


'''
run:

00000123

'''

 



answered Oct 18 by avibootz
0 votes
# Formatting a table

# Print column headers
print(f"{'Name':<15}{'Age':<10}{'Salary':<12}")

# Print data rows
print(f"{'Darth ':<15}{30:<10}{95000.0:<12.2f}")
print(f"{'Luna':<15}{42:<10}{102000.0:<12.2f}")


'''
run:

Name           Age       Salary      
Darth          30        95000.00    
Luna           42        102000.00   

'''

 



answered Oct 18 by avibootz
...