在Python中,我們可以使用f-string、%運算子和format()方法來示範字串插值。字串插值是將動態資料或變數插入字串的過程。當使用變數或表達式形成字串時,它非常有用,而無需使用任何字串格式化或字串連接。在本文中,我們將看到如何使用Python進行字串插值。
一個f-string是一個以f 或F開頭的字串字面值。前綴f或F表示該字串是一個f-string。字串中包含用花括號{}括起來的表達式。這些表達式可以具有在運行時評估的動態值。
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.
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
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.
Example
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程式範例,示範字串插值的詳細內容。更多資訊請關注PHP中文網其他相關文章!