共計 778 個字符,預計需要花費 2 分鐘才能閱讀完成。
format 命令是 Python 中用于格式化字符串的一個方法,它可以讓我們動態地插入變量值到字符串中。
使用 format 方法的一般語法如下:
formatted_string = "string with {} and {}".format(value1, value2)
在這個語法中,大括號 {}
表示插入點,我們可以在大括號中指定要插入的變量。在 format 方法中,我們按照順序將要插入的變量作為參數傳遞給 format 方法。
我們也可以通過索引來指定要插入的變量的位置,例如:
formatted_string = "string with {1} and {0}".format(value1, value2)
在這個例子中,{1}
的位置插入了 value1
的值,{0}
的位置插入了 value2
的值。
另外,我們還可以使用鍵值對的形式來指定要插入的變量,例如:
formatted_string = "string with {name} and {age}".format(name="John", age=25)
在這個例子中,{name}
的位置插入了 "John"
,{age}
的位置插入了25
。
format 方法也支持格式化輸出,我們可以在大括號中使用冒號 :
來指定格式化的方式。例如:
formatted_string = "The value is {:.2f}".format(3.14159)
在這個例子中,{:.2f}
表示要將插入的值格式化為浮點數,并保留 2 位小數。
除了 format 方法,Python 3.6 及以上版本還引入了更方便的 f -string 語法,它以 f
開頭,并使用花括號包含變量名。例如:
name = "John"
age = 25
formatted_string = f"string with {name} and {age}"
這樣就可以在字符串中直接使用變量的值,而不需要使用 format 方法。
丸趣 TV 網 – 提供最優質的資源集合!
正文完