Python string formatting

# Welcome to TutorialShore!
# Today we will discuss Formatted String Literals
# and format method of String class in python
# Let me start writing a program to greet a student with their grade.

name = “Oyster”
grade = 8.568

message = ‘Hello ‘ + name + ‘! You scored ‘ + str(grade) + ‘.’

# ideally we want a string like
message = ‘Hello name! You scored grade.’

# To use formatted string literals (also called f-strings for short),
# begin a string with f before the opening quotation mark.
# Inside the string, you can write a Python expression or variable
# wrapped by curley brackets.

message = f’Hello {name}! You scored {grade:.2f}.’ # specify format for the field 10.2f

# You can use F instead of f and F-strings work with double and triple quotes also.

# Python String has a method called format.
# Let us explore that method
message = ‘Hello {}! You scored {:.2f}.’.format( # automatic field numbering
name, grade
)

message = ‘Hello {0}! You scored {1:.2f}. Bye {0}’.format( # manual field specification
name, grade # positional arguments
)

message = ‘Hello {name}! You scored {grade:.2f}. Bye {name} :)’.format(
name=name, grade=grade # keyword arguments
)

# The studen
student = {
“name”: “Oyster”,
“grade”: 8.456,
“subject”: “CS”
}

message = ‘Hello {name}! You scored {grade:.2f} in {subject}. Bye {name} :)’.format(
name=student[‘name’], grade=student[‘grade’], subject=student[‘subject’] # keyword arguments
)

message = ‘Hello {name}! You scored {grade:.1f} in {subject}. Bye {name} :)’.format(
**student # double asterisk operator for keyword arguments
)

print(message)

My Thought

Your email address will not be published. Required fields are marked *

Our Tool : hike percentage calculator