String Formatting in Python
String formatting is about inserting values (like variables or calculations) into text in a clean and readable way. It's very useful when you want to create messages, reports, or display data to users.
Python has three main ways to do this. We'll start with the newest and easiest (f-strings), then look at the older methods for comparison.
f-strings (Formatted String Literals) – The Recommended Way
f-strings are the modern and preferred way since Python 3.6. You prefix the string with 'f' and put expressions inside curly braces {}. They are fast, readable, and allow direct variable insertion or even calculations.
str.format() Method
Before f-strings, str.format() was the standard way. You use {} placeholders and call .format() with values. It's flexible and good for when you need to reuse the same format with different data.
Old % Operator (Legacy Style)
This is the oldest way, similar to C's printf. It still works but is not recommended for new code because it's less readable and more error-prone.
Formatting Numbers
All methods allow precise number formatting, like fixed decimal places or adding commas for thousands.
Which Method to Use?
Use f-strings for new code – they're the fastest and easiest to read. Use str.format() when you need more complex formatting or compatibility with older Python versions. Avoid % formatting unless working with legacy code.
Quick Quiz
Hemos revisado y comprobado los materiales, pero aún pueden existir errores. El contenido se ofrece únicamente con fines educativos, así que úsalo bajo tu propia responsabilidad y verifica con otras fuentes si es necesario.
✨ Pregunta a Lara — tu compañera de estudio con IA
Desbloquea soporte de aprendizaje personalizado. Lara puede explicar lecciones, resumir temas y responder tus preguntas — disponible desde el plan Go y superiores.
Lara te ayuda a aprender más rápido — exclusivo para los miembros ReadyTools Go, Plus y Max.


