Skip to content

Python String Formatting | % Operator

  • by

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
Python String Formatting | % Operator

In this tutorial, you will learn about  “Old Style” String Formatting (% operator).

Syntax :

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

Argument

Here are some basic argument specifiers you have to know:

  • String – %s
  • Integers (Number) – %d
  • Floating point numbers  %f
  • 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')

Output:

Padding and aligning Python String Formatting

Do comment if you have any suggestion or doubt.

Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Python String Formatting are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading