我经常要向用户提供文字段落。我对将文本呈现给用户所知道的一切都很好(通常使用\n
或文本换行使其在用户方面令人满意)但是有没有办法在我的实际代码中返回回车没有\n
a = "this is a really long line of text that i need to show to the user. this is a really long line of text that i need to show to the user. this is a really long line of text that i need to show to the user. this is a really long line of text that i need to show to the user."
b = "this is a really long line of text that i need to show to the user.\n
this is a really long line of text that i need to show to the user.\n
this is a really long line of text that i need to show to the user.\n"
所以我的目标是打破'在我的代码中使用美学上令人愉悦的块,但仍然使用wordwrap将文本显示给用户。我知道这样做的唯一方法是在' b'但这不适用于自动换行
答案 0 :(得分:3)
所以你希望它在你的实际代码中可读吗? Python将隐式地连接代码中的相邻字符串。要使它跨线工作,您可以使用行继续符\
,或者最好将其包装在括号中。
a = ("This is a really long\n"
"line of text that I\n"
"need to show to the user.")
print(a)
答案 1 :(得分:1)
您可以使用三重引号,例如
b = """this is a really long line of text that i need to show to the user.
this is a really long line of text that i need to show to the user.
this is a really long line of text that i need to show to the user."""
# no \n needed, but carriage returns happen on every newline
或者您可以使用自动字符串连接
# THIS DOESN'T WORK
b = "this is a really long line of text that i need to show to the user."
"this is a really long line of text that i need to show to the user."
"this is a really long line of text that i need to show to the user."
# also no \n needed, but this is one long line of text.
糟糕,对罗杰·范的出色回答的评论提醒我,如果不将它包在括号中或使用续行符\
b = ("this is a really long line of text that i need to show to the user."
"this is a really long line of text that i need to show to the user."
"this is a really long line of text that i need to show to the user.")
# OR
b = "this is a really long line of text that i need to show to the user."\
"this is a really long line of text that i need to show to the user."\
"this is a really long line of text that i need to show to the user."
答案 2 :(得分:1)
将字符串放在括号中,然后利用Python自动连接相邻字符串文字。然后你可以在你想要的代码中放置文本周围的任何空白格式。
b = ("this is a really long line of text that i need to show to the user."
"this is a really long line of text that i need to show to the user."
"this is a really long line of text that i need to show to the user.")
答案 3 :(得分:0)
您可以使用带有三引号的“heredoc”:
b =
'''
this is a really long line of text that i need to show to the user.
this is a really long line of text that i need to show to the user.
this is a really long line of text that i need to show to the user.
'''