介紹
Python 支援使用 +
運算子來進行字串串接。在大多數其他程式語言中,如果我們將一個字串與整數(或任何其他原始資料型別)串接起來,語言會自動將它們轉換為字串,然後再進行串接。
然而,在 Python 中,如果你嘗試使用 +
運算子將一個字串與一個整數串接起來,你將會得到一個執行時錯誤。
範例
讓我們看一個使用 +
運算子來串接字串(str
)和整數(int
)的範例。
string_concat_int.py
current_year_message = 'Year is '
current_year = 2018
print(current_year_message + current_year)
期望的輸出是字串:Year is 2018
。然而,當我們執行這段程式碼時,我們會得到以下的執行時錯誤:
Traceback (most recent call last):
File "/Users/sammy/Documents/github/journaldev/Python-3/basic_examples/strings/string_concat_int.py", line 5, in <module>
print(current_year_message + current_year)
TypeError: can only concatenate str (not "int") to str
那麼在 Python 中該如何將 str
和 int
進行串接呢?有多種其他方法可以執行這個操作。
先決條件
為了完成本教程,您需要:
- 熟悉安裝Python 3以及熟悉使用Python編程。 如何在Python 3中編程系列或使用VS Code進行Python編程。
此教程已在Python 3.9.6上進行測試。
使用str()
函數
我們可以將一個int
作為參數傳遞給str()
函數,它將被轉換為str
類型:
print(current_year_message + str(current_year))
整數current_year
被轉換為字符串:Year is 2018
。
使用%
插值運算符
我們可以使用printf風格的字符串格式化將值傳遞給轉換規格:
print("%s%s" % (current_year_message, current_year))
整數current_year
被插值為字符串:Year is 2018
。
使用str.format()
函数
我们也可以使用str.format()
函数来连接字符串和整数。
print("{}{}".format(current_year_message, current_year))
整数current_year
被强制转换为字符串:Year is 2018
。
使用f-strings
如果你使用的是Python 3.6或更高版本,也可以使用f-strings。
print(f'{current_year_message}{current_year}')
整数current_year
被插值为字符串:Year is 2018
。
结论
你可以从我们的GitHub存储库查看完整的Python脚本和更多Python示例。
Source:
https://www.digitalocean.com/community/tutorials/python-concatenate-string-and-int