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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
