String Formatting WITH Problems and Solution

String Formatting WITH Problems and Solution

What is String Formatting?


It is the way to insert custom string or variable in a text (string).

Using string formatting, a developer want required output in different style.


Why need of formatting a string?


To display string in proper understanding form, We need to format a string properly.

To display content dynamically, because we use different variable to format a string.

If we did not use string formatting, then we will be unable to display dynamically content.


Different style to format a string

Different styles are used in Python to format a string:

  • Formatting with % Operator (Old)
  • Formatting with format() method (New)
  • Formatting with f-strings
  • Formatting with String Template ClassDifferent styles are used in Python to format a string:
  • Formatting with % Operator (Old)
  • Formatting with format() method (New)
  • Formatting with f-strings
  • Formatting with String Template Class


NO#1: Formatting with % Operator (Python 2).

Introduction:

It is the oldest method of string formatting. We use the modulo % operator (“string-formatting operator”).

So, ‘%s’ is used for string, ‘%d’ for integers, ‘%f’ for float, ‘%b’ for binary format.

Syntax:

print("%modulo operator" % variable)

Examples:

name = "Faisal"

age = 434

price = 243.43

print("Hi, %s" % name)

print("My age is, %d" % age)

print("Product price is, %f" % price)

print("My Name is %s and my age is, %i" %(name, age))


NO#2: Formatting with Format() (Python 3)

Introduction:

format method introduced in Python3. It easy way to format string than modulo operator. We used curly braces and specific number (0,…) of variable as we used.

Syntax:

print(“{0} {1} {2}”.format(variable1, variable1, variable1))

Examples:

print("{0} {1} price ${2}".format(100, 'rushikesh', 2.14)) # positional arguments

print("{quantity} {item} price ${price}".format(quantity=10, item='rushikesh', price=2.14))

# Keyword arguments

Result:

100 rushikeshprice $2.14

10 rushikeshprice $2.14


NO#3: Formatting with f-strings (3.6+).

Introduction:

This method is introduced in python3.6+ version which is advanced method to format a string in Python.


Syntax:

print(f"Hi I am {variable} and my age is {variable}")

print(f"Hi I am {expression} and my age is {variable}")


Examples:

name = "Rushikesh"

age = 323

print(f"Hi I am {name} and my age is {age}")


Result:

Hi I am Rushikesh and my age is 323


NO#4: Formatting with Template Class

Introduction:

Template class in string module, added since Python 2.4. To use Template class, we need to use $ValidIdentifier as placeholder in template string.


Example:

from string import Template

str = 'Hi $name, you age is $age'

template_obj = Template(str)

template_obj.substitute(name=‘Rushikesh Reddy', age=34)


Result:

'Hi Rushikesh Reddy, your age is 34'


要查看或添加评论,请登录

社区洞察

其他会员也浏览了