How to Use String format() Method in PythonPython Basics


The string format() method formats the given string into a better output in Python.

Example

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

print("{1} {0} {1}".format("hello", "world"))
print("{1} {0} {0}".format("hello", "world"))
print("{1} {1} {1}".format("hello", "world"))
print("{0} {0} {0}".format("hello", "world"))

Output:

world hello world
world hello hello
world world world
hello hello hello

Syntax

template.format(p0, p1, ..., k0=v0, k1=v1, ...)

Parameters

Name Description
positional parameters List of parameters that can be accessed with the index of the parameter inside curly braces {index}
Keyword parameters List of parameters of type key=value, that can be accessed with the key of the parameter inside curly braces {key}

Return Value

It returns the formatted string.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us