学堂 学堂 学堂公众号手机端

在Python中,可以使用字符串的format()方法或者f-string来插入变量的值到字符串中

lewis 2年前 (2023-11-30) 阅读数 10 #技术

在Python中,可以使用字符串的format()方法或者f-string来插入变量的值到字符串中。

使用format()方法:

name="Alice" age=30 sentence="Mynameis{}andIam{}yearsold.".format(name,age) print(sentence)

使用f-string:


name="Alice" age=30 sentence=f"Mynameis{name}andIam{age}yearsold." print(sentence)

这两种方法都可以将变量的值插入到字符串中。f-string是Python3.6及以上版本引入的新特性,更简洁方便。

版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门