3 min read•june 24, 2024
Python's formatted strings, or , revolutionize . They allow seamless embedding of expressions and variables within , making code more readable and efficient. F-strings support various formatting options, giving developers precise control over output appearance.
Mastering f-strings opens up a world of possibilities for string formatting. From aligning text and padding output to controlling number precision and adding separators, f-strings offer powerful tools for creating polished, professional-looking output in Python programs.
f"Hello, {name}!"
)name = "Alice"; f"Hello, {name}!"
)f"The result is: {calculate_result()}"
)[{value:format_specifier}](https://www.fiveableKeyTerm:{value:format_specifier})
[{count:d}](https://www.fiveableKeyTerm:{count:d})
), 'f' for floating-point numbers ([{price:f}](https://www.fiveableKeyTerm:{price:f})
), 'e' or 'E' for scientific notation ({[value:e](https://www.fiveableKeyTerm:value:e)}
), and '%' for percentage formatting ([{percentage:%}](https://www.fiveableKeyTerm:{percentage:%})
).n
after the , where n is the desired number of decimal places ({[price:.2f](https://www.fiveableKeyTerm:price:.2f)}
rounds the price to two decimal places)[{value:,}](https://www.fiveableKeyTerm:{value:,})
formats the value with comma separators)[{value:>10}](https://www.fiveableKeyTerm:{value:>10})
right-aligns the value with a width of 10){value:10}
formats the value with a minimum width of 10 characters)[{value:->10}](https://www.fiveableKeyTerm:{value:->10})
right-aligns the value with a width of 10 and uses '-' as the padding character)[{price:^10.2f}](https://www.fiveableKeyTerm:{price:^10.2f})
centers the price within a width of 10 characters and rounds it to two decimal places)