Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,624 questions

56,911 answers

573 users

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 3 days ago by avibootz
0 votes
# Left-align "Hello" in a field 10 characters wide
result = f"{'Hello':<10}"

print(f"|{result}|")


'''
run:

|Hello     |

'''

 



answered 3 days ago by avibootz
0 votes
number = 123

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

print(result)


'''
run:

00000123

'''

 



answered 3 days ago 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 3 days ago by avibootz
...