如何提高Python代码中段落的可读性
我经常需要把一段段文字展示给用户。我对如何把文字呈现给用户还算满意(通常是用\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"
所以我的目标是把'a'分成看起来更好看的小块,在代码里这样做,但在展示给用户时仍然使用自动换行。我知道的唯一方法在'b'里展示了,但那样做不支持自动换行。
4 个回答
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.
'''
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.")
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.
哎呀,Roger Fan 的精彩回答下的评论提醒我,如果不把它放在括号里或者使用换行符 \
,是不能这样做的。
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."
3
你想让代码更易读吗?在Python中,紧挨着的字符串会自动连接在一起。如果你想让字符串跨越多行,可以使用换行符\
,或者更好的是,把它放在括号里。
a = ("This is a really long\n"
"line of text that I\n"
"need to show to the user.")
print(a)