<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Coder Legion - Recent posts tagged formatting</title>
<link>https://coderlegion.com/tag/formatting</link>
<description>Powered by Question2Answer</description>
<item>
<title>Introducing PrettyPrint — a PHP array pretty-printer with Python-/PyTorch-style formatting</title>
<link>https://coderlegion.com/20586/introducing-prettyprint-php-array-pretty-printer-with-python-pytorch-style-formatting</link>
<description>&lt;p&gt;I'm excited to announce PrettyPrint, a small, zero-dependency PHP utility designed to format numeric arrays in a clean, readable style inspired by Python and the tensor-views you’ll see in PyTorch.&lt;/p&gt;
&lt;p&gt;Whether you're doing ML experiments, debugging data pipelines, logging arrays, or building educational tools, PrettyPrint makes it easier to inspect array data in a structured way.&lt;/p&gt;
&lt;h3 id=&quot;why-use-prettyprint-&quot;&gt;Why use PrettyPrint?&lt;/h3&gt;
&lt;p&gt;No extra dependencies - just pure PHP.&lt;/p&gt;
&lt;p&gt;Supports aligned 2D tables, summarized tensor-style views (for larger arrays), 3D tensor with head/tail blocks, and flexible output options (labels, controlling newline behaviour, etc.).&lt;/p&gt;
&lt;p&gt;Makes your array dumps more readable and visually helpful.&lt;/p&gt;
&lt;h3 id=&quot;quick-start-amp-examples&quot;&gt;Quick Start &amp;amp; Examples&lt;/h3&gt;
&lt;h4 id=&quot;installation&quot;&gt;Installation&lt;/h4&gt;
&lt;pre&gt;&lt;code class=&quot;language-github&quot;&gt;composer require apphp/pretty-print
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;global-helper-functions&quot;&gt;Global helper functions&lt;/h4&gt;
&lt;p&gt;You can use the &lt;code&gt;pprint()&lt;/code&gt; helper function for quick prints:&lt;/p&gt;
&lt;p&gt;Print scalars/strings&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-php&quot;&gt;pprint('Hello', 123, 4.56);
// Output:
// Hello 123 4.5600
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;1D / 2D examples&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-php&quot;&gt;// Print multiple 1D rows aligned as a 2D table
pprint([1, 23, 456], [12, 3, 45]);
// Output:
// [[  1,  23, 456],
//  [12,   3,  45]]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Label + 2D matrix&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-php&quot;&gt;pprint('Confusion matrix:', [[1,23], [456,7]]);
// Output:
// Confusion matrix:
// [[   1,  23],
//  [ 456,   7]]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tensor / summarization example&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-php&quot;&gt;$matrix = [
    [1, 2,  3,  4,  5],
    [6, 7,  8,  9, 10],
    [11,12, 13, 14, 15],
];
pprint($matrix);
// Output:
// tensor([
//   [  1,   2,   3,   4,   5],
//   [  6,   7,   8,   9,  10],
//   [ 11,  12,  13,  14,  15]
// ])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And for summarization (showing just head + tail of rows/cols):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-php&quot;&gt;pprint($matrix, headRows:1, tailRows:1, headCols:2, tailCols:2);
// Output:
// tensor([
//   [  1,   2,  ...,   4,   5],
//   ...,
//   [ 11,  12,  ...,  14,  15]
// ])
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You can even print 3D tensor-like structures with summarised blocks:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-php&quot;&gt;$tensor3d = [
    [[1,2,3],[4,5,6]],
    [[7,8,9],[10,11,12]],
    [[13,14,15],[16,17,18]],
];
pprint($tensor3d, headB:1, tailB:1, headRows:1, tailRows:1, headCols:1, tailCols:1);
// Output:
// tensor([
//  [[ 1,  ...,  3],
//   [ 4,  ...,  6]],
//
//  ...,
//
//  [[13,  ..., 15],
//   [16,  ..., 18]]
// ])
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;object-style-usage&quot;&gt;Object-style usage&lt;/h4&gt;
&lt;p&gt;If you prefer, you can instantiate the printer as an object:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-php&quot;&gt;use Apphp\PrettyPrint\PrettyPrint;

$pp = new PrettyPrint();
$pp('Hello', 42);       // same as pprint('Hello', 42)

$pp($tensor3d, headB:2, tailB:1, headRows:1, tailRows:1, headCols:1, tailCols:1);
$pp('Metrics:', [[0.91, 0.02], [0.03, 0.88]]);
&lt;/code&gt;&lt;/pre&gt;
&lt;h4 id=&quot;options-reference&quot;&gt;Options reference&lt;/h4&gt;
&lt;p&gt;Here are a few of the core options you can pass:&lt;/p&gt;
&lt;p&gt;&lt;code&gt;end (string)&lt;/code&gt; — line terminator (default: newline) &lt;br&gt;
&lt;code&gt;headB / tailB (ints)&lt;/code&gt; — number of 2D blocks shown for 3D tensors &lt;br&gt;
&lt;code&gt;headRows / tailRows&lt;/code&gt; — number of head/tail rows per slice with ellipsis between &lt;br&gt;
&lt;code&gt;headCols / tailCols&lt;/code&gt; — number of head/tail columns per slice with ellipsis between &lt;/p&gt;
&lt;p&gt;Named-argument syntax (PHP 8+) is supported, or you can pass an array of options as last parameter. &lt;/p&gt;
&lt;h4 id=&quot;where-it-shines&quot;&gt;Where it shines&lt;/h4&gt;
&lt;p&gt;ML/AI workflows: When you have numeric arrays or tensors in PHP (or imported from elsewhere) and want human-readable dumps.&lt;/p&gt;
&lt;p&gt;Debugging &amp;amp; logging: Replace ad-hoc &lt;code&gt;var_dump()&lt;/code&gt; or &lt;code&gt;print_r()&lt;/code&gt; with structured, aligned table views.&lt;/p&gt;
&lt;p&gt;Educational/teaching code: When showing matrix/tensor examples and you want a cleaner presentation.&lt;/p&gt;
&lt;p&gt;CLI &amp;amp; scripts: For quick visual inspection of matrices/tensors in terminal output.&lt;/p&gt;
&lt;h4 id=&quot;final-thoughts&quot;&gt;Final thoughts&lt;/h4&gt;
&lt;p&gt;I believe PrettyPrint fills a small but useful niche for PHP developers working with numeric data or coming from Python/PyTorch mindsets - offering readability, alignment, summarization, and minimal overhead.&lt;/p&gt;
&lt;p&gt;Give it a spin:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;GitHub: &lt;a rel=&quot;nofollow&quot; href=&quot;https://github.com/apphp/pretty-print&quot;&gt;https://github.com/apphp/pretty-print&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Packagist: &lt;a rel=&quot;nofollow&quot; href=&quot;https://packagist.org/packages/apphp/pretty-print&quot;&gt;https://packagist.org/packages/apphp/pretty-print&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;I'd love your feedback, suggestions for enhancements, or contributions — open an issue or PR and let’s make this tool even better together!&lt;/p&gt;
&lt;p&gt;Happy coding!&lt;/p&gt;
</description>
<category>Articles</category>
<guid isPermaLink="true">https://coderlegion.com/20586/introducing-prettyprint-php-array-pretty-printer-with-python-pytorch-style-formatting</guid>
<pubDate>Sun, 14 Jun 2026 14:40:50 +0000</pubDate>
</item>
<item>
<title>You should know these f-string tricks in Python</title>
<link>https://coderlegion.com/304/you-should-know-these-f-string-tricks-in-python</link>
<description>&lt;h2&gt;Introduction&lt;/h2&gt;
&lt;p&gt;While Python programming is getting popular, mastering string formatting is foundational for every Python programmer! &lt;strong&gt;F-strings&lt;/strong&gt;, introduced in Python 3.6, offer a different way to embed variables and expressions into strings, significantly improving code readability and maintainability. This guide compromises of advanced tips and tricks for using f-strings, helping you leverage their full potential.&lt;/p&gt;
&lt;h2&gt;Demostration&lt;/h2&gt;
&lt;h3&gt;1. String Interpolation and Variable Names&lt;/h3&gt;
&lt;p&gt;By wrapping variables within curly braces, you can effortlessly embed their values into your text. Additionally, f-strings offer a unique feature that allows you to display both the variable name and its value, facilitating debugging and code comprehension.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Define the variables
name = 'Cindy'
age = 30
        
#Display the values of the variables
print(f'{name} {age}')
        
# Display variable names alongside their values
print(f'{name=}, {age=}')
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=260983676083709970&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;div class=&quot;div-blue&quot;&gt;
&lt;span class=&quot;alert-header&quot;&gt;Note:&lt;/span&gt;
  &lt;span class=&quot;alert-body&quot;&gt;The second example is known as &lt;strong&gt;self-documenting expression&lt;/strong&gt;, which is introduced in Python 3.8. It can assist debugging by providing contextual information within the output.&lt;/span&gt;
&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;Other formatting methods&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;name = 'Cindy'
age = 30

# Using %-formatting
print('%s %d' % (name, age))

# Using str.format()
print('{} {}'.format(name, age))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=3607732438567287575&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;You may see that &lt;strong&gt;f-strings&lt;/strong&gt; can format and display the value in a more organized way compared to other formatting methods.&lt;/p&gt;
&lt;h3&gt;2. Formatting Expressions&lt;/h3&gt;
&lt;p&gt;F-strings allow you to format the output of expressions directly within the string, presenting the data precisely based on your needs. For instance, you can specify formatting options such as &lt;strong&gt;precision for floating-point numbers&lt;/strong&gt;, &lt;strong&gt;alignment for text&lt;/strong&gt;, and &lt;strong&gt;padding for both text and numbers&lt;/strong&gt;. &lt;/p&gt;
&lt;pre&gt;&lt;code&gt;number = 25.644524

# 1. Format numeric value to two decimal places
print(f'{number:.2f}') 
    
# 2. Left, center, and right alignment
text = &quot;HelloWorld&quot;
print(f'{text:&amp;lt;20}')   # Left aligned
print(f'{text:^20}')   # Center aligned
print(f'{text:&amp;gt;20}')   # Right aligned
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=2913808129899862146&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Other formatting methods&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;number = 25.644524

# Using %-formatting
print('%.2f' % number)

# Using str.format()
print('{:.2f}'.format(number))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=14205458135527832553&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;While other formatting method also allow you to format the floating number, f-strings offer alignment and padding format in a more convenient way.&lt;/p&gt;
&lt;h3&gt;3. Inline Arithmetic and Function Calls&lt;/h3&gt;
&lt;p&gt;Moreover, f-strings also include arithmetic operations and function calls directly within the string interpolation. This allows you to perform calculations and call functions dynamically as part of the string formatting, reducing the need for intermediate variables and making your code more efficient and concise.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;a = 32
b = 19

# 1. Inline arithmetic operations
print(f'{a + b}')
print(f'{a * b}')

# 2. Inline function calls
import math
radius = 10
print(f'Area of circle: {math.pi * radius ** 2:.2f}')
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=10279437635672425788&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Other formatting methods&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;a = 32
b = 19

# Using %-formatting
print('%d' % (a + b))
print('%d' % (a * b))

# Using str.format()
print('{}' .format(a + b))
print('{}' .format(a * b))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=9507528005366772981&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3&gt;4. Inline Arithmetic and Function Calls&lt;/h3&gt;
&lt;p&gt;F-strings allow you to include conditional logic directly within the string interpolation using Python's &lt;strong&gt;ternary conditional operator&lt;/strong&gt;. This makes it possible to dynamically adjust the content and formatting of the string based on specific conditions, enhancing code readability and flexibility.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;gender = &quot;M&quot;

# Conditional formatting
print(f'Gender is {&quot;Male&quot; if gender == &quot;M&quot; else &quot;Female&quot;}')
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=2265986397078312729&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Practical Scenario&lt;/strong&gt;
&lt;/p&gt;&lt;pre&gt;&lt;code&gt;temperature = 33
print(f'Temperature is {&quot;hot&quot; if temperature &amp;gt; 30 else &quot;cold&quot; if temperature &amp;lt; 15 else &quot;moderate&quot;}')
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=13933123246324385885&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;h3&gt;5. Advanced String Manipulation&lt;/h3&gt;
&lt;p&gt;F-strings facilitate advanced string manipulation tasks such as slicing, concatenation, and applying string methods.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;text = &quot;Welcome to F-Strings!&quot;

# Slicing and concatenation
print(f'{text[:5]} {text[-6:]}')

# Applying string methods
print(f'{text.lower()}')
print(f'{text.replace(&quot;Welcome&quot;, &quot;Hello&quot;)}')
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=7882619120343779513&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;In addition to basic interpolation, f-strings can be used for more complex string manipulation tasks. You can perform slicing, concatenation, and apply various string methods within the f-string syntax. This makes f-strings a powerful tool for handling and transforming string data efficiently, often reducing the need for additional lines of code.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Other formatting methods&lt;/strong&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;text = &quot;Welcome to F-Strings!&quot;

# Using %-formatting
print('%s %s' % (text[:5], text[-6:]))
print('%s' % text.lower())
print('%s' % text.replace(&quot;Welcome&quot;, &quot;Hello&quot;))

# Using str.format()
print('{} {}'.format(text[:5], text[-6:]))
print('{}'.format(text.lower()))
print('{}'.format(text.replace(&quot;Welcome&quot;, &quot;Hello&quot;)))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;img src=&quot;https://logiclair.org/?qa=blob&amp;amp;qa_blobid=12698367846099033382&quot; alt=&quot;&quot;&gt;&lt;/p&gt;
&lt;p&gt;From the comparison, you might see that f-strings offer shorter can cleaner code, and thus improve readability and understandability compared to others.&lt;/p&gt;
&lt;h2&gt;Wrapping Up&lt;/h2&gt;
&lt;p&gt;F-strings provide a powerful and efficient way to format strings in Python. From basic interpolation to advanced string manipulation and conditional formatting, f-strings streamline code and improve readability. By mastering these advanced tips and tricks, you can enhance your Python programming skills and write more maintainable code. Happy Coding!&lt;/p&gt;
</description>
<category>Python</category>
<guid isPermaLink="true">https://coderlegion.com/304/you-should-know-these-f-string-tricks-in-python</guid>
<pubDate>Tue, 28 May 2024 22:46:17 +0000</pubDate>
</item>
</channel>
</rss>