Python String Formatting is used to replace fields contained within a string to define how individual values are presented (like Example 22 is easy). Here is number 22 can be changed as per requirements. In this tutorial, you will learn about it, how to do it. In Python, there is two way to formatting strings.
- % operator
- Built-in format() function – Passed directly
In this tutorial, you will learn about “Old Style” String Formatting (% operator).
Special symbols like “%s” and “%d” enclosed in a “tuple“, which contains normal text are used to format a string. For simple using place string just use % operator, here you want.
'%s %s' % ('one', 'two') # OR "Hello, %s!" % name
Here are some basic argument specifiers you have to know:
- String –
- Integers (Number) –
- Floating point numbers
- Up to Floating point numbers right of the dot –
%.<number of digits>f
Python String Formatting Example
This is a simple example of string formatting, placing content(text) in the string. The %s the format specifier is told Python was to substitute the value of
name, represented as a string.
name = "Eyehunt" print("Hello, %s!" % name)
Output: Hello, Eyehunt!
Another example with a tuple.
print('one %d two %d' % (1, 2))
Output: one 1 two 2
Padding and aligning strings
Printing in a console after 10 space. This is left side padding example, you can do the same with the right side.
print('%10s' % 'Print')
Do comment if you have any suggestion or doubt.
Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Python String Formatting are in Python 3, so it may change its different from python 2 or upgraded versions.