Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python - String Formatting



String formatting in Python is the process of building a string representation dynamically by inserting the value of numeric expressions in an already existing string. Python's string concatenation operator doesn't accept a non-string operand. Hence, Python offers following string formatting techniques −

Using % operator

The "%" (modulo) operator often referred to as the string formatting operator. It takes a format string along with a set of variables and combine them to create a string that contain values of the variables formatted in the specified way.

Example

To insert a string into a format string using the "%" operator, we use "%s" as shown in the below example −

name = "Tutorialspoint"print("Welcome to %s!" % name)

It will produce the followingoutput

Welcome to Tutorialspoint!

Using format() method

It is a built-in method ofstr class. The format() method works by defining placeholders within a string using curly braces "{}". These placeholders are then replaced by the values specified in the method's arguments.

Example

In the below example, we are using format() method to insert values into a string dynamically.

str = "Welcome to {}"print(str.format("Tutorialspoint"))

On running the above code, it will produce the followingoutput

Welcome to Tutorialspoint

Using f-string

The f-strings, also known as formatted string literals, is used to embed expressions inside string literals. The "f" in f-strings stands for formatted and prefixing it with strings creates an f-string. The curly braces "{}" within the string will then act as placeholders that is filled with variables, expressions, or function calls.

Example

The following example illustrates the working of f-strings with expressions.

item1_price = 2500item2_price = 300total = f'Total: {item1_price + item2_price}'print(total)

The output of the above code is as follows −

Total: 2800

Using String Template class

The String Template class belongs to the string module and provides a way to format strings by using placeholders. Here, placeholders are defined by a dollar sign ($) followed by an identifier.

Example

The following example shows how to use Template class to format strings.

from string import Template# Defining template stringstr = "Hello and Welcome to $name !"# Creating Template objecttemplateObj = Template(str)# now provide valuesnew_str = templateObj.substitute(name="Tutorialspoint")print(new_str)

It will produce the followingoutput

Hello and Welcome to Tutorialspoint !
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp