![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements