python

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

小亿
145
2024-03-02 14:09:20
栏目: 编程语言
Python开发者服务器,限时0元免费领! 查看>>

在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及以上版本引入的新特性,更简洁方便。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:Python怎么查找子字符串在字符串中的位置索引

0
看了该问题的人还看了