Tuesday 30 March 2021

String Format in Python

Formatting string enables the capability to add dynamic content or string to it in an easy way. It allows to update contents in a string in simpler way.

String Format using format () method

Syntax: template_string.format(positional_args, keyword_args) 

The template string contains the replacement fields which can be replaced using the positional_args and keyword_args used in the method. The method returns the formatted string.

In the template string, the replacements fields are enclosed within curly braces “{  }”. Rest of the string content remains unchanged.

Using positional arguments

print('{0} {1} the {2} nicely'.format('This', 'formats', 'string'))

 


Here, <template_string> is '{0} {1} the {2} nicely'. The replacement fields are {0}, {1}, and {2} with zero-based positional arguments 'This', 'formats', 'string'. The replacements fields are replaced with the corresponding positional arguments by the format method.

 

Using keyword arguments

print('{name} is {age} years old'.format(name='Python', age= 30))

 


Here, the replacement fields are {name}, {age}and the corresponding keyword arguments with values. Each fields are replaced with corresponding keyword argument values.

Lambda Function in Python

 

Lambda Function

Lambda function is a function, which is defined without a name (anonymous). Hence, named as anonymous function. Lambda function is defined using the keyword lambda that’s why it also called as lambda function.

Lambda functions are syntactically restricted to a single expression. However, can have multiple arguments separated with commas. Semantically, lambda functions are just syntactic sugar for a normal function definition. Lambda functions can be used wherever function objects are required.

 

Using lambda function

syntax- lambda args: expression

pow = lambda x: x**2

print(pow(2))


Here, x is the argument to the lambda function and x**2 is the expression which gets assigned to the variable ”pow” after evaluation. 

Notice, the lambda function has no name and doesn’t contain any parentheses unlike normal function.

The above lambda function is similar to:

def pow(x):

    return x**2