在Python中,可以使用format函數來對字符串進行格式化操作。format函數的基本使用方法如下:
name = 'Alice'
age = 25
message = 'My name is {} and I am {} years old.'.format(name, age)
print(message)
輸出:My name is Alice and I am 25 years old.
name = 'Bob'
age = 30
message = 'My name is {name} and I am {age} years old.'.format(name=name, age=age)
print(message)
輸出:My name is Bob and I am 30 years old.
name = 'Charlie'
age = 35
message = 'My name is {name} and I am {} years old.'.format(age, name=name)
print(message)
輸出:My name is Charlie and I am 35 years old.
name = 'Dave'
age = 40
message = 'My name is {0} and I am {1} years old.'.format(name, age)
print(message)
輸出:My name is Dave and I am 40 years old.
pi = 3.1415926
message = 'The value of pi is {:.2f}.'.format(pi)
print(message)
輸出:The value of pi is 3.14.
以上只是format函數的一些基本用法,還可以通過format函數進行更復雜的格式化操作,比如對日期、時間等進行格式化。詳細的用法可以參考Python官方文檔。