Sitemap
Press enter or click to view image in full size

String formatting in Python!

2 min readDec 5, 2024

--

1. Old-Style Formatting (%):

This is the oldest way for formatting. Generally people ar enot using it!

This uses placeholders like %s or %d for formatting

%s used for string and %d for integers.

name = "Jackson"
age = 30
print("My name is %s and I am %d years old." % (name, age))
OUTPUT__My name is Jackson and I am 30 years old.

2.format( ) Method:

this allows more readability and flexibility.We can just give empty arguments in the string and at last use — .format(what are the things you wanted to pass in those empty arguments in order).

name = "Himanshu"
passion = "singing"
print("I am {} and I love {}.".format(name, passion))
OUTPUT__I am Himanshu and I love singing

You can also positional or keyword arguments

print("I love {1} and {0}.".format("Python", "JavaScript"))
OUTPUT__I love JavaScript and Python.

Here 0 given for 1st argument in the format() and 1 for the next.if there are more ,2 comes next and so on…..

3. f-Strings:

This is the latest format used very comfartable to use. The most modern and concise way to format strings.

subject= "python"
print(f"{subject} is easy")

We can directly give the variable in the arguments no need to use any keyword but at starting we have to use (f” (and close it at end)”)

OUTPUT__python is easy

like this we can print any numbers or strings just by passing the variable into the arguments.

Get Lakshmipriyaperavali’s stories in your inbox

Join Medium for free to get updates from this writer.

It also supports expressions inside curly braces:

age=22
print(f"In 5 years, I will be {age + 5} years old.")
OUTPUT__In 5 years, I will be 27 years old.

For decimal point numbers we use float to print int:

sqrt2 = 1.41421356

print(f"sqrt2 is rounded as: {sqrt2:.2f}")

here sqrt2 is rounded to two decimal points as we mentioned(.2) and f represents the float

OUTPUT__sqrt2 is rounded as: 1.41

Format strings handle different data types (e.g., integers, floats, strings, dates) without mentioning them seperately.

So we can use all these methods to format out strings.!!

--

--