🎓 All Courses | 📚 Python Programming Syllabus

📋 Study this course on TaskLoco
#python-programming#strings#formatting

String Formatting — All Methods

f-strings (Python 3.6+) — USE THESE:

name = "Alice"
pi = 3.14159
print(f"Hello {name}")
print(f"Pi is {pi:.2f}")      # 2 decimal places
print(f"{1000000:,}")          # 1,000,000
print(f"{0.856:.1%}")          # 85.6%
print(f"{name!r}")             # repr: 'Alice'
print(f"{name:>20}")           # right-align in 20 chars

.format() method:

"{} is {}".format("Alice", 30)
"{name} is {age}".format(name="Alice", age=30)
"{0:.2f}".format(3.14159)  # 3.14

% formatting (old style, avoid):

"Hello %s, you are %d" % ("Alice", 30)

Format spec cheat sheet:

:.2f — 2 decimal places

:, — thousands separator

:>10 — right align width 10

:<10 — left align width 10

:^10 — center width 10

:05d — zero-padded integer


YouTube • Top 10
Python Programming: String Formatting Deep Dive
Tap to Watch ›
📸
Google Images • Top 10
Python Programming: String Formatting Deep Dive
Tap to View ›

Reference:

Wikipedia: String Interpolation

image for linkhttps://en.wikipedia.org/wiki/String_interpolation

📚 Python Programming — Full Course Syllabus
📋 Study this course on TaskLoco

TaskLoco™ — The Sticky Note GOAT