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
在下面给出的示例中,我们将采用与上面相同的示例,但我们将set设置为一个带括号的换行符
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.')