Python - 讓長字串排版變好看
Posted on Aug 2, 2018 in Python 程式設計 - 初階 by Amo Chen ‐ 1 min read
Python 是注重排版的程式語言,如果排版排得不好,閱讀的時候就會無來由的感到痛苦。
其中長字串的排版也是有些學問的,可以善用幾個小秘訣讓排版變好看,拯救壞心情!
通常長字串最常見的情況會是:
if condition:
text = '''\
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nunc urna lacus, feugiat iaculis lorem ac, rhoncus maximus est.
Fusce rhoncus rutrum massa et luctus.
Sed finibus dapibus lacus, et bibendum quam sollicitudin sed.
'''
else:
text = '''\
Curabitur quis dolor vel nibh elementum efficitur.
Donec sit amet mattis magna, eget sollicitudin urna.
Duis nunc dui, sodales in aliquam et, sollicitudin id elit.
Nullam nec tellus erat.
'''
上述的範例是否已經帶來心氣不順的症狀?
提供 2 招不錯的方式幫忙讓上述範例變好看。
textwrap.dedent
textwrap 是 Python 內建的 module ,專門處理一些文字相關的功能,其中 dedent
專門用來移除每一行開頭的空白。所以上述範例可以改成:
from textwrap import dedent
if condition:
text = dedent('''\
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nunc urna lacus, feugiat iaculis lorem ac, rhoncus maximus est.
Fusce rhoncus rutrum massa et luctus.
Sed finibus dapibus lacus, et bibendum quam sollicitudin sed.
''')
else:
text = dedent('''\
Curabitur quis dolor vel nibh elementum efficitur.
Donec sit amet mattis magna, eget sollicitudin urna.
Duis nunc dui, sodales in aliquam et, sollicitudin id elit.
Nullam nec tellus erat.
''')
有沒有變美!
小括號
除了用 dedent
之外,可以用小括號改善長字串的排版:
if condition:
text = (
'Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n'
'Nunc urna lacus, feugiat iaculis lorem ac, rhoncus maximus est.\n'
'Fusce rhoncus rutrum massa et luctus.\n'
'Sed finibus dapibus lacus, et bibendum quam sollicitudin sed.\n'
)
else:
text = (
'Curabitur quis dolor vel nibh elementum efficitur.\n'
'Donec sit amet mattis magna, eget sollicitudin urna.\n'
'Duis nunc dui, sodales in aliquam et, sollicitudin id elit.\n'
'Nullam nec tellus erat.\n'
)
請注意,上述範例每一行的結尾不需要 ,
,這是因為 Python 支援此種串接語法。
以上就是 Python 關於長字串的小秘訣, Happy Coding!
References
https://docs.python.org/3.6/reference/lexical_analysis.html#string-literal-concatenation
https://docs.python.org/3.6/library/textwrap.html