溫馨提示×

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

小億
126
2024-03-02 14:09:20
欄目: 編程語言

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

0