2 min read•june 24, 2024
in Python offers powerful tools for creating dynamic text. From simple placeholders to precise numerical formatting, it allows for flexible and readable code. Understanding these techniques is crucial for effective string manipulation and presentation.
The method, alignment specifications, and precision controls provide fine-grained control over output. Mastering these concepts enables programmers to generate well-formatted strings for various applications, from user interfaces to data reporting.
[{}](https://www.fiveableKeyTerm:{})
{}
or contain a field name {field_name}
format()
method
format()
in the order corresponding to the placeholders"Hello, {}! My name is {}.".format("Alice", "Bob")
outputs "Hello, Alice! My name is Bob."[<](https://www.fiveableKeyTerm:<)
(left-align), [^](https://www.fiveableKeyTerm:^)
(center-align), or [>](https://www.fiveableKeyTerm:>)
(right-align) characters
"Left: {:<10} | Center: {[:^](https://www.fiveableKeyTerm::^)10} | Right: {[:>](https://www.fiveableKeyTerm::>)10}".format("Apple", "Banana", "Cherry")
outputs "Left: Apple | Center: Banana | Right: Cherry"[.n](https://www.fiveableKeyTerm:.n)
syntax, where n
is the number of decimal places
f
: Fixed-point notation (default for floating-point)[e](https://www.fiveableKeyTerm:e)
: Exponential notation[g](https://www.fiveableKeyTerm:g)
: General format (uses fixed-point for small numbers, exponential for large numbers)[d](https://www.fiveableKeyTerm:d)
: Decimal integer (default for integers)"Fixed: {:.2f}, Exponential: {:.2e}, General: {:.2g}".format(3.14159)
outputs "Fixed: 3.14, Exponential: 3.14e+00, General: 3.1"%
operator for string formatting