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

王林
发布: 2023-09-19 10:53:19
转载
1034 人浏览过

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方法和%操作符这样的方法来创建字符串插值。在本文中,我们通过示例了解了所有三种方法。

以上是Python程序示例,演示字符串插值的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!