0% found this document useful (0 votes)
3 views3 pages

Python String Formatting Guide

Uploaded by

sandboxpmu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views3 pages

Python String Formatting Guide

Uploaded by

sandboxpmu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🐍 Python Format — Detailed Guide

✨ Variables

name1 = 'alex'
name2 = 'rami'

We have two variables:

• name1 → 'alex'
• name2 → 'rami'

1. Using .format() Method

✅ Basic example

print('first name is: {}'.format(name1))

📝 Explanation:

• {} is a placeholder inside the string.


• .format(name1) replaces {} with the value of name1 .
• Output:

first name is: alex

✅ Multiple placeholders

print('first name is: {}, last name is: {}'.format(name1, name2))

📝 Explanation:

• The first {} → name1


• The second {} → name2
• Output:

first name is: alex, last name is: rami

1
✅ Using index numbers

print('last name is: {1}, first name is: {0}'.format(name1, name2))

• {0} = name1
• {1} = name2

📝 Output:

last name is: rami, first name is: alex

2. Using f-Strings (Python 3.6+)

✅ Simple example

print(f'{name1} {name2}')

📝 Output:

alex rami

✅ More descriptive

print(f'first name is: {name1}')


print(f'last name is: {name2}')

📝 Output:

first name is: alex


last name is: rami

✅ Multiple values in one print

print(f'first name is: {name1}', f'last name is: {name2}')

📝 Output:

2
first name is: alex last name is: rami

3. .format() vs f-String Comparison

Feature .format() f-string

Syntax 'text {}'.format(var) f'text {var}'

Readability Longer Cleaner

Performance Slightly slower Faster

Supports expressions Yes Yes

Python version required All 3.6+

✅ Final Example

name1 = 'alex'
name2 = 'rami'

# Using .format()
print('first name is: {}'.format(name1))
print('last name is: {}'.format(name2))
print('first name is: {}, last name is: {}'.format(name1, name2))

# Using f-strings
print(f'{name1} {name2}')
print(f'first name is: {name1}', f'last name is: {name2}')

🖨 Output:

first name is: alex


last name is: rami
first name is: alex, last name is: rami
alex rami
first name is: alex last name is: rami

📌 Tip: f-strings are generally preferred for new Python code because they are faster, more readable,
and easier to maintain.

You might also like