How To Use Python Format Function With Examples

Python has a format function that can be used to format text strings output. Let’s give a brief description of the format function, and then introduce how to use it.

1. Python Format Function Description.

The format function is used to format strings in Python, it has a strong ability to format output. The format function is often used in conjunction with a python text string.

2. The Python Format Function Examples.

The Python format function can accept any number of parameters, you can reference the parameter’s value in the formatted string with {parameter index number} format. For example, use {0} to reference the first parameter of the format function, {1} will reference the second parameter of the format function. If you do not specify the parameter index number in {}, then it will assign the format function parameters to the {} placeholder by the default order.

# Pass the format function's parameter to the {} placeholder by in default order.
>>>"{} {}".format("hello", "world")
'hello world'

# Use the {parameter index number} placeholder to specify the format function parameters position in the formated string.
>>> "{1} {0}".format("hello", "world") 
'world hello'

>>> "{2} {0} {1}".format("are", "you","how")
'how are you'

We can also pass the format function’s parameters in a python dictionary object, but we should add ** before the python dictionary object when passing it.

>>> dict = {'name':'Jerry','coding':'python'}
>>> 
>>> "{name} like {coding} programming.".format(**dict)
'Jerry like python programming.'
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Clicky
0
Would love your thoughts, please comment.x
()
x