Linux 拨号vps windows公众号手机端

Python怎么在字符串中插入变量的值

lewis 9年前 (2016-11-08) 阅读数 9 #程序编程
文章标签 python

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

使用format()方法:

name = "Alice"
age = 30
sentence = "My name is {} and I am {} years old.".format(name, age)
print(sentence)

使用f-string:

name = "Alice"
age = 30
sentence = f"My name is {name} and I am {age} years old."
print(sentence)

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

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门