InPython, we use string formatting to control how text is displayed. It allows us to insert values intostrings and organize the output in a clear and readable way. In this article, we’ll explore different methods of formatting strings in Python to make our code more structured and user-friendly.
Using f-string
f-strings are the simplest and most efficient way to format strings. They allow expressions to be evaluated at runtime and are preceded by "f"
or "F"
.
Example:
Python# to display name and agename="shakshi"age=21print(f"Name:{name}, Age:{age}")# to display the sum of a and ba=5b=3print(f"sum of{a} and{b} is{a+b}")
OutputName: shakshi, Age: 21sum of 5 and 3 is 8
Using format()
format() is one of the methods in string class which allows the substitution of the placeholders with the values to be formatted.
Example:
Pythonname="shakshi"age=21# Using positional argumentsprint("Name:{0}, Age:{1}".format(name,age))# Using keyword argumentsprint("Name:{name}, Age:{age}".format(name="shakshi",age=21))
OutputName: shakshi, Age: 21Name: shakshi, Age: 21
Explanation:
- Positional Arguments:This inserts values in order using placeholders {}.
- Keyword Arguments:This uses named parameters for clarity and flexibility in value assignment.
Using format specifier (% )
%
operator for string formatting is the oldest method in Python and is similar to C-style string formatting. It’s still widely used but is less efficient compared to f-strings andformat()
.
Most common format specifiers
Format specifier | Description |
---|
%s | Specifies the String |
%c | Specifies a single character |
%d | Specifies the integer |
%f | Specifies the float. Any number of digits can be present after decimal point |
%<space>.<number>f | Specifies the float. <space> denotes the number of space to append before printing the number. <number> denotes the number of digits to be present after the decimal point. |
%x / %X | Specifies the hexadecimal representation of the value |
%o | Specifies the octal representation of a value |
%e / %E | Specifies the floating numbers in exponential format |
%g / %G | Similar to %e/%E. Specifies the exponential format only if the exponent is greater than -4 |
Example:
Pythona="This is a string"print("String is%s"%(a))# single characterb='a'print("Single character is%c"%(b))# integerc=45print("number is%d"%(c))# float without specified precisiond=34.521094print("float is%f"%(d))
OutputString is This is a stringSingle character is anumber is 45float is 34.521094
Using print()
print()
function in Python displays messages and outputs, converting non-string objects to strings. It also allows formatting with parameters likesep
, which defines a separator between printed elements.
Example:
Pythonname="shakshi"age=21print("Name: "+name+", Age: "+str(age))
OutputName: shakshi, Age: 21