let username = "Alice";let points = 1250;let level = 15;println(f"Welcome back, {username}!");println(f"You have {points} points and are at level {level}.");println(f"Next level in {2000 - points} points!");
fn divide : a, b { if b == 0 { return f"Error: Cannot divide {a} by zero"; } return a / b;}println(divide(10, 2)); // 5println(divide(10, 0)); // Error: Cannot divide 10 by zero
let user_id = 12345;let action = "login";let timestamp = "2024-01-15 14:30:00";println(f"[{timestamp}] User {user_id} performed action: {action}");// [2024-01-15 14:30:00] User 12345 performed action: login
let name = "Alice";let order_id = "ORD-12345";let items_count = 3;let total = 99.99;let message = f"Order ConfirmationHi {name},Your order {order_id} has been confirmed!Items: {items_count}Total: ${total}Thank you for your purchase!";println(message);
F-strings are evaluated at runtime. For frequently used strings, consider building them once and reusing:
// Less efficient in a loopfor i in 0..1000 { let msg = f"Processing item {i}"; // ...}// More efficient if base doesn't changelet base = "Processing item ";for i in 0..1000 { let msg = base + str(i); // ...}
// Harder to readprintln(f"Result: {((a + b) * c / d) ** 2 + (x - y)}");// Betterlet part1 = ((a + b) * c / d) ** 2;let part2 = x - y;let result = part1 + part2;println(f"Result: {result}");
Use f-strings for user-facing messages
F-strings make it easy to create dynamic, readable messages:
// Good for user messagesprintln(f"Welcome, {user_name}! You have {msg_count} new messages.");// Good for logsprintln(f"[ERROR] Failed to load file: {filename}");// Good for reportsprintln(f"Sales: ${revenue:.2f} ({growth}% growth)");
Combine with type conversion when needed
Use str() for explicit type conversion in f-strings:
let count = 42;// Automatic conversion in f-stringsprintln(f"Count: {count}");// Explicit conversion if neededlet message = "Count: " + str(count);