
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
What does % do to strings in Python?
% is a string formatting operator or interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to using the sprintf() in the C language. For example,
>>> lang = "Python" >>> print "%s is awesome!" % lang Python is awesome
You can also format numbers with this notation. For example,
>>> cost = 128.527 >>> print "The book costs $%.2f at the bookstore" % cost The book costs $128.53 at the bookstore
You can also use dictionaries to interpolate strings. They have a syntax in which you need to provide the key in the parentheses between the % and the conversion character. For example,
print('%(language)s has %(number)03d quote types.' % {'language': "Python", "number": 2}) Python has 002 quote types.
You can read up more about string formatting and their operators here: https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
- Related Articles
- What does "print >>" do in python?
- What does [::-1] do in Python?
- What does reload() function do in Python?
- What does raw_input() function do in python?
- What does input() function do in python?
- What does print() function do in Python?
- What does open() function do in Python?
- What does close() function do in Python?
- What does os.pipe() function do in Python?
- What does the &= operator do in Python?
- What does getattr() function do in Python?
- What does hasattr() function do in Python?
- What does method time.tzset() do in Python?
- What does the >> operator do in Python?
- What does an object() method do in Python?

Advertisements