卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章20761本站已运行3410

Python程序示例,演示字符串插值

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 are expressions that are enclosed in curly braces. 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 these placeholders are taken from the .format() 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 format() method specifies the values at these 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方法和%操作符这样的方法来创建字符串插值。在本文中,我们通过示例了解了所有三种方法。

卓越飞翔博客
上一篇: 笔尖上的魔术师:掌握PHP对接Midjourney,创造出非凡的AI绘画之旅
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏