Python String format()教程

Python String format()教程

Python String format()教程

  了解Python中的字符串格式化。字符串格式化也称为字符串插值。这是在预定义文本中插入自定义字符串或变量的过程。可以使用它在图表中插入标题、显示消息或错误,或者将语句传递给函数

Python String format()教程
Python String format()教程

  本文,晓得博客为你介绍Python String format()使用教程。

String format()方法

  格式化方法:位置格式、格式化的字符串文字、模板法

  我们将由一对花括号定义的占位符放在文本中。我们称之为字符串点格式方法。然后,我们将所需的值传递给该方法。该方法使用按出现顺序替换值的值替换占位符:

'text{}'.format(value)
位置格式

  我们定义一个字符串并插入两个占位符。我们将两个字符串传递给该方法,将传递这两个字符串以获得以下输出:

print("Machine learning provides {} the ability to learn {}".format("systems", "automatically"))

输出:
Machine learning provides systems the ability to learn automatically
String-format方法占位
Python String format()教程

  我们可以为字符串和传递给方法的值使用变量。在下面的示例代码中,我们定义了一个带有占位符和其他两个变量的字符串。我们使用两个定义的变量将格式方法应用于字符串。该方法读取字符串并用给定值替换占位符。

my_string = "{} rely on {} datasets"
method = "Supervised algorithms"
condition = "labeled"

print(my_string.format(method, condition))

输出:
Supervised algorithms rely on labeled datasets

  还可将索引号添加到占位符中以重新排序值。这会影响方法替换占位符的顺序。该方法将它们替换为给定顺序的值。如果我们添加索引号,替换顺序会相应更改。

  推荐:如何使用Python破解ZIP压缩文件密码

名称占位符

  我们还可以引入由关键字名称调用的关键字参数。在占位符中插入了关键字。然后,我们在format方法中调用这些关键字。然后,我们分配将为它们中的每一个传递哪个变量,从而产生以下输出。

tool="Unsupervised algorithms"
goal="patterns"
print("{title} try to find {aim} in the dataset".format(title=tool, aim=goal))

输出:
Unsupervised algorithms try to find patterns in the dataset
String-format方法名称占位符
Python String format()教程

  定义了一个带有键的字典:工具和目标。将它们的值插入到一个字符串中。在占位符内,我们可以使用括号表示法指定与变量数据的关键工具关联的值。数据是方法中指定的字典,工具是该字典中存在的键。

my_methods = {"tool": "Unsupervised algorithms", "goal": "patterns"}
print('{data[tool]} try to find {data[goal]} in the dataset'.format(data=my_methods))

输出:
Unsupervised algorithms try to find patterns in the dataset

  推荐:Python append()函数

格式说明符

  我们还可以在花括号内指定格式。这定义了如何呈现单个值。在这里,我们将使用语法索引冒号说明符。最常见的格式说明符之一是浮点数,由f.在代码中,我们指定以索引0传递的值将是一个浮点数。

String-format方法格式说明符
Python String format()教程
print("Only {0:f}% of the {1} produced worldwide is {2}!". format(0.5155675, "data", "analyzed"))

输出:
Only 0.515567% of the data produced worldwide is analyzed!

  我们还可以添加.2f表示我们希望浮点数有两位小数,如结果输出所示。

print("Only {0:.2f}% of the {1} produced worldwide is {2}!".format(0.5155675, "data", "analyzed"))

输出:
Only 0.52% of the data produced worldwide is analyzed!

总结

  以上是晓得博客为你接受的Python String format()教程的全部内容,通过了解有关位置格式的更多信息,更快速的学习了解Python。

  推荐:零基础如何开始学习Python

给文章评分

晓得博客,版权所有丨如未注明,均为原创
晓得博客 » Python String format()教程

转载请保留链接:https://www.pythonthree.com/python-string-format/

Claude、Netflix、Midjourney、ChatGPT Plus、PS、Disney、Youtube、Office 365、多邻国Plus账号购买,ChatGPT API购买,优惠码XDBK,用户购买的时候输入优惠码可以打95折

Chatgpt-Plus注册购买共享账号
滚动至顶部