溫馨提示×

Python中字符串格式化的操作是什么

小億
85
2024-03-12 16:01:40
欄目: 編程語言

Python中字符串格式化的操作是通過使用字符串的format()方法或者使用%操作符來將變量插入到字符串中。下面是兩種字符串格式化的示例:

使用format()方法:

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

使用%操作符:

name = "Bob"
age = 25
sentence = "My name is %s and I am %d years old" % (name, age)
print(sentence)

這兩種方法都可以實現(xiàn)字符串格式化的操作,選擇其中一種來使用即可。

0