String Formatting

In this section we will learn various approaches to format strings in Python and PowerShell and what are the similarities between these approaches.

-f Format Operator in PowerShell :

PowerShell provides a '-f' operator called as the Format operator to perform string formatting, where left-hand side of operator is a String with placeholders denoted by squiggly brackets ( {} ) and right-hand side is an array of values to place into the place holder string on the left.

Syntax:

"this is {0} a string {1}" -f $value1, $value2

It is a must to define each placeholder with the index of element on right hand side so that the values are placed correctly, first element of the array of values start at '0'

Python String Formatting : .format()

Python has a similar Built-in .format() method for formatting the strings, which can be applied on any string on the left using the Dot ( . ) operator and accepts values as arguments that will passed into the placeholders in the string.

Syntax:

"this is {} a string {}".format(value1, value2) Alternatively with index numbers "this is {0} a string {1}".format(value1, value2)

It is not mandatory to define the index inside a placeholder and Python automatically assumes the placeholder value in the sequence they are defined in format() method as a argument.

NOTE:

This is just a teaser content from my book in form of a blog post!

If you want to know more about Common String Operations, String Interpolation, Escape characters, String slicing (sub-string) and built-in string methods in Python and PowerShell, t hen read my book (below) which is still in progress, on lean publishing format.

Buy early, pay less, free updates!