Hone logo
Hone
Problems

Mastering F-Strings: Dynamic String Formatting in Python

F-strings (formatted string literals) provide a concise and readable way to embed expressions inside string literals. This challenge will test your understanding of f-strings and their ability to dynamically generate strings by incorporating variables and expressions. Successfully completing this challenge demonstrates proficiency in a core Python feature for string manipulation.

Problem Description

You are tasked with creating a function called format_string that takes a name (string) and an age (integer) as input and returns a formatted string using an f-string. The formatted string should read: "Hello, my name is [name] and I am [age] years old."

Key Requirements:

  • The function must accept two arguments: name (a string) and age (an integer).
  • The function must return a string formatted using an f-string.
  • The returned string must precisely match the specified format: "Hello, my name is [name] and I am [age] years old."
  • The values of name and age should be dynamically inserted into the string.

Expected Behavior:

The function should correctly substitute the provided name and age into the f-string, producing the expected output.

Edge Cases to Consider:

  • Empty name: The function should still work correctly if the name argument is an empty string ("").
  • Zero age: The function should handle an age of 0 without errors.
  • Non-integer age: While the problem specifies an integer age, consider how your solution would behave if a different data type were passed. (This is not a requirement to handle, but good to think about).

Examples

Example 1:

Input: name = "Alice", age = 30
Output: "Hello, my name is Alice and I am 30 years old."
Explanation: The function substitutes "Alice" for [name] and 30 for [age] in the f-string.

Example 2:

Input: name = "", age = 25
Output: "Hello, my name is  and I am 25 years old."
Explanation: The function handles an empty name correctly, resulting in a space where the name would be.

Example 3:

Input: name = "Bob", age = 0
Output: "Hello, my name is Bob and I am 0 years old."
Explanation: The function correctly handles an age of 0.

Constraints

  • name will be a string.
  • age will be an integer.
  • The function must be named format_string.
  • The returned string must be exactly as specified in the problem description, including spaces.

Notes

  • F-strings are prefixed with an f before the opening quote.
  • Variables are embedded within curly braces {} inside the f-string.
  • Consider the readability and conciseness of your solution. F-strings are designed to be easy to understand.
  • You are not required to perform any input validation (e.g., checking if age is a positive number). The problem assumes valid input.
Loading editor...
python