Python / Core Python Fundamentals Interview Questions
What are the different ways to format strings in Python, and which is preferred?
Python has three main approaches to string formatting, each with different trade-offs.
name, score = 'Alice', 95.5 # 1. % formatting (old-style, C printf-inspired) print('Name: %s, Score: %.1f' % (name, score)) # 2. str.format() (Python 2.6+ / 3) print('Name: {}, Score: {:.1f}'.format(name, score)) print('Name: {n}, Score: {s:.1f}'.format(n=name, s=score)) # named # 3. f-strings (Python 3.6+ â preferred) print(f'Name: {name}, Score: {score:.1f}') print(f'Score rounded: {round(score)}') # expressions inside {}
F-strings are the modern standard and are recommended for all new code. They are faster than str.format(), more readable, and evaluate expressions inline. The colon inside the braces introduces format specifiers: {value:.2f} formats a float to two decimal places; {value:>10} right-aligns in a 10-character field; {value:,} adds thousands separators.
Python 3.12 extended f-strings to allow reusing the same quote character inside braces, removing a previous restriction. For very long template strings (email bodies, SQL queries) that are composed at runtime, str.format_map() or template strings from the string module may be cleaner than a giant f-string.
More Related questions...