首頁  >  文章  >  後端開發  >  Python程式範例,示範字串插值

Python程式範例,示範字串插值

王林
王林轉載
2023-09-19 10:53:191054瀏覽

Python程式範例,示範字串插值

在Python中,我們可以使用f-string、%運算子和format()方法來示範字串插值。字串插值是將動態資料或變數插入字串的過程。當使用變數或表達式形成字串時,它非常有用,而無需使用任何字串格式化或字串連接。在本文中,我們將看到如何使用Python進行字串插值。

Method 1 : Using f-string

一個f-string是一個以f F開頭的字串字面值。前綴f或F表示該字串是一個f-string。字串中包含用花括號{}括起來的表達式。這些表達式可以具有在運行時評估的動態值。

Example

In the below example, we create three variables namely name, age, and height whose values are initialized. A message is created using an f-string in which name, age, and height 是The value of these expressions is taken from the variables(name, age, and height) at runtime.

name = 'John'
age = 25
height = 1.75

message = f"My name is {name}. I am {age} years old and {height} meters tall."
print(message)

輸出

My name is John. I am 25 years old and 1.75 meters tall.

Method 2 : Using the format() method

The format() method is used to do string interpolation by inserting values in a string using placeholders. These placeholders are represented in the string using curly braces {}. The values at the place the string using curly braces {}. The values at the place placeue. () attribute at the end of the string.

Example

In the below example, we first initialize three variables namely name, age, and height. We then create a message using a string with placeholders in it represented by curly braces{}.The formaties odue.The fors value specs specus specus specus fors specjue. placeholders.

name = 'John'
age = 25
height = 1.75

message = "My name is {}. I am {} years old and {} meters tall.".format(name, age, height)
print(message)

輸出

My name is John. I am 25 years old and 1.75 meters tall.

Method 3 : Using the % operator

The % operator works similarly to the use of % operators in printf() function in C-programming. The string contains expressions in the form of %s,%d,%f, etc which specify the type of value for example %s specifies string,%d specifies integer,%f specifies float value, etc.

Example

在下面的範例中,我們初始化了三個變量,分別是name、age和height,然後使用%運算子建立了一個訊息字串。字串包含了以佔位符形式指定的表達式,這些表達式使用%s、%d和%f來表示。這些佔位符的值是透過元組傳遞給%運算子的。

name = 'John'
age = 25
height = 1.75

message = "My name is %s. I am %d years old and %.2f meters tall." % (name, age, height)
print(message)

輸出

My name is John. I am 25 years old and 1.75 meters tall.

結論

字串插值可讓您建立一個包含變數和表達式的字串。這些表達式或變數的值是動態的,並在運行時取得。 Python提供了像f-string、format方法和%運算元這樣的方法來建立字串插值。在本文中,我們透過範例了解了所有三種方法。

以上是Python程式範例,示範字串插值的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除