0% found this document useful (0 votes)
4 views2 pages

Python String Formatting Methods

The document outlines four string formatting methods in Python: Percent (%) Formatting, which is the oldest method using % symbols; the .format() method, which uses {} placeholders for flexibility; and f-Strings, the newest and easiest method introduced in Python 3.6 that allows direct variable insertion. It also mentions the use of the modulus operator for string formatting, which is similar to its mathematical use. Each method is illustrated with examples for clarity.

Uploaded by

saipreethi8050
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)
4 views2 pages

Python String Formatting Methods

The document outlines four string formatting methods in Python: Percent (%) Formatting, which is the oldest method using % symbols; the .format() method, which uses {} placeholders for flexibility; and f-Strings, the newest and easiest method introduced in Python 3.6 that allows direct variable insertion. It also mentions the use of the modulus operator for string formatting, which is similar to its mathematical use. Each method is illustrated with examples for clarity.

Uploaded by

saipreethi8050
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 String Formatting Methods

1. Percent (%) Formatting (Old Style Formatting)


This is the oldest method of string formatting in Python. It uses % symbols similar to C language.
Common specifiers: %s for string, %d for integer, %f for float.
Example:
name = 'Preethi'
age = 20
print('My name is %s and I am %d years old.' % (name, age))
Float example:
price = 99.4567
print('Price = %.2f' % price)
(.2f means 2 decimal places)

2. .format() Method (Dot Format Method)


This method uses {} placeholders and is more flexible than % formatting.
Example:
name = 'Preethi'
age = 20
print('My name is {} and I am {} years old.'.format(name, age))
Float example:
num = 12.5678
print('Value = {:.2f}'.format(num))

3. Modulus (%) Operator in Strings


The modulus operator % is used to insert values into a string placeholder.
Example:
marks = 85
print('Your marks are %d' % marks)
Note: % is also used in math to find remainder, but in strings it formats values.

4. f-Strings (f' ') — Modern Method


This is the newest and easiest method (Python 3.6+). Variables are written directly inside {}.
Example:
name = 'Preethi'
age = 20
print(f'My name is {name} and I am {age} years old.')
Float example:
pi = 3.14159
print(f'Pi value = {pi:.2f}')
Summary:
Percent formatting - Old method
.format() - Flexible method
Modulus % - Same as percent formatting in strings
f-strings - Newest and easiest method

You might also like