如何在Python中換行?
字串是字元的集合,可以表示單個單詞或整個句子。與Java不同,不需要顯式宣告Python字串,可以直接將字串值賦給字面量。
Python中的字串由字串類表示,該類提供多個函式和方法,可以使用這些函式和方法對字串執行各種操作。
在本文中,我們將瞭解如何在Python中換行。
使用帶括號的換行符
一種方法是使用帶括號的換行符。使用Python在括號、方括號和大括號內推斷的續行是換行長行的推薦方法。
如果需要,可以在表示式周圍新增額外的括號。我們必須將這些帶括號的換行符應用於要換行的長行。
示例1
在下面的示例中,我們以字串作為輸入,並使用列表帶括號的換行符將其換行。
str1 = "Welcome to Tutroialspoint" print("The given string is") print(str1) print("After wrapping the line") res = list(str1) #Using parenthesized line break (list) print(res)
輸出
上述示例的輸出為:
The given string is Welcome to Tutroialspoint After wrapping the line ['W', 'e', 'l', 'c', 'o', 'm', 'e', ' ', 't', 'o', ' ', 'T', 'u', 't', 'r', 'o', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't']
示例2
在下面的示例中,我們將採用與上述相同的示例,但我們將集合作為帶括號的換行符。
str1 = "Welcome to Tutroialspoint" print("The given string is") print(str1) print("After wrapping the line") res = set(str1) #Using parenthesized line break (set) print(res)
輸出
上述示例的輸出為:
The given string is
Welcome to Tutroialspoint
After wrapping the line
{'i', 'W', 'o', 'T', 'a', 'p', 'm', 'r', 'l', 'c', ' ', 'u', 'n', 'e', 't', 's'}
使用“\”運算子
您還可以使用“\”運算子在Python中換行。如果您使用反斜槓,它看起來會更好。確保續行正確縮排。最好在二元運算子之後而不是之前進行換行。我們必須仔細縮排反斜槓附近的空格,它必須位於兩行之間。
示例
在下面的示例中,我們以字串作為輸入,並使用反斜槓運算子換行。
str1 = """This s a really long line, but we can make it across multiple lines.""" print("The given string is ") print(str1) print("Wrapping the given input") res = 'This s a really long line,', \ 'but we can make it across multiple lines.' #Wrapping the line using backslash print(res)
輸出
上述示例的輸出為:
The given string is
This s a really long line,
but we can make it across multiple lines.
Wrapping the given input
('This s a really long line,', 'but we can make it across multiple lines.')
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP