
- 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
How to compare Python string formatting: % with .format?
% can either take a variable or a tuple. So you'd have to be very explicit about what you want it to do. For example, if you try formatting such that −
Example
my_tuple = (1, 2, 3) "My tuple: %s" % my_tuple You'd expect it to give the output: My tuple: (1, 2, 3)
Output
But it will throw a TypeError. To guarantee that it always prints, you'd need to provide it as a single argument tuple as follows −
"hi there %s" % (name,) # supply the single argument as a single-item tuple
Remembering such caveats every time is not that easy and may cause bugs. .format doesn't have those issues. format is also very clean looking comparatively.
- Related Articles
- How to compare two dates in String format in Java?
- String Formatting in Python using %?
- String Formatting Operator in Python
- How to compare string and number in Python?
- How to print a complete tuple in Python using string formatting?
- String Formatting with ToString in C#
- Formatting Minute in m format in Java
- Formatting day in d format in Java
- Formatting day in dd format in Java
- How to compare Python DateTime with Javascript DateTime?
- How does string formatting work in PowerShell?
- How to format string using PowerShell?
- How to configure handling and formatting of log file in Selenium with python?
- String Formatting in C# to add padding
- Formatting day of week in EEEE format in Java

Advertisements