欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > 能源 > 5.2章节python字符串的格式化三种方式

5.2章节python字符串的格式化三种方式

2025/6/29 13:21:02 来源:https://blog.csdn.net/qq_55433305/article/details/144474513  浏览:    关键词:5.2章节python字符串的格式化三种方式

在Python中,格式化字符串是编程中常见的任务,它用于将变量或表达式的值嵌入到字符串中。以下是三种常见的格式化字符串的方式:

1.百分号(%)格式化:

这是Python早期版本中常用的字符串格式化方法。通过在字符串中插入百分号(%)和格式说明符,可以将变量的值插入到字符串中。

name = "Alice"
age = 30
scroe = 99.236
formatted_string = "Name: %s, Age: %d, scroe: %f" % (name, age,scroe)
print(formatted_string)
print("Name: %s, Age: %d, scroe: %.2f" % (name, age,scroe))

在这里插入图片描述

2.f-strings(格式化字符串字面量):

从Python 3.6开始引入,f-strings提供了一种非常简洁和直观的字符串格式化方式。通过在字符串前加上字母f或F,并在字符串内部使用大括号({})直接嵌入变量或表达式。

name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")# 也可以在大括号中直接进行表达式计算
formatted_string_with_expression = f"Name: {name}, Age: {age + 5}"
print(formatted_string_with_expression)
# 输出: Name: Alice, Age: 35

3.str.format()方法:

从Python 2.7开始引入,str.format()方法提供了一种更灵活和强大的字符串格式化方式。通过在大括号({})中指定占位符,并在format()方法中按顺序或关键字参数传递值。

name = "Alice"
age = 30
formatted_string = "Name: {}, Age: {}".format(name, age)
print(formatted_string)
# 输出: Name: Alice, Age: 30# 也可以指定顺序
formatted_string_with_order = "Name: {1}, Age: {0}".format(age, name)
print(formatted_string_with_order)
# 输出: Name: Alice, Age: 30# 还可以指定变量名
formatted_string_with_key = "Name: {name}, Age: {age}".format(name=name, age=age)
print(formatted_string_with_key)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词