避免在 Python 中列印字串時使用引號
如果我們按原樣列印給定的字串列表,則必須使用引號並在適當的地方填充一對匹配的引號。我們可以透過採用以下兩種方法避免在列印語句中使用引號。
使用 join()
join 方法透過使用我們選擇的任意分隔符,幫助我們列印列表元素的輸出。在下面的示例中,我們選擇 ** 作為分隔符。
示例
list = ['Mon', 'Tue', 'Wed']
# The given list
print("The given list is : " + str(list))
print("The formatted output is : ")
print(' ** '.join(list))輸出
執行以上程式碼將得到以下結果 −
The given list is : ['Mon', 'Tue', 'Wed'] The formatted output is : Mon ** Tue ** Wed
使用 sep 關鍵字
sep 關鍵字也可以用於提供格式化的輸出,而無需大量使用引號。
示例
list = ['MOn', 'Tue', 'Wed']
# The given list
print("The given list is : " + str(list))
print("The formatted output is : ")
print("list, sep =' - '")輸出
執行以上程式碼將得到以下結果 −
The given list is : ['MOn', 'Tue', 'Wed'] The formatted output is : MOn ** Tue ** Wed MOn - Tue - Wed
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP