วิธีการใช้ textwarp เพื่อทำการนำข้อความที่ยาวเกินไปมาขึ้นบรรทัดใหม่
Posted: 04/11/2019 2:57 pm
textwarp คือ โมดูลที่ใช้สำหรับอำนวยความสะดวกเกี่ยวกับข้อความ สามารถใช้ให้ทำการขึ้นบรรทัดใหม่ได้ ซึ่งจะเป็นโมดุลที่ใช้ในงานใน Python โดยการใช้นั้นจะต้องทำเรียกใช้หรือ import เข้ามาใช้ตัวของ textwarp จะมีฟังก์ชั่นอยู่ 3 ตัว คือ wrap() จะใช้สำหรับการย่อหน้าและการเข้าบรรทัดใหม่ ส่วนของ fill() ความสามารถจะคล้ายกับตัวของ wrap ตัวฟังก์ชั่น dedent() จะใช้สำหรับการลบช่องว่างที่นำหน้าออกจากทุกบรรทัดในของข้อความ โดยทั้ง 3 อย่างนี้มีตัวอย่างประกอบดังนี้
ฟังก์ชั่น wrap(text, width=70, **kwargs)
Output
ฟังก์ชั่น fill(text, width=70, **kwargs)
Output
ฟังก์ชั่น dedent(text)
Output
อ้างอิง
https://docs.python.org/2/library/textwrap.html
https://www.geeksforgeeks.org/textwrap-text-wrapping-filling-python/
https://pymotw.com/3/textwrap/
ฟังก์ชั่น wrap(text, width=70, **kwargs)
Code: Select all
import textwrap
text = 'This function wraps the input paragraph such that each line in the paragraph is at most width characters long. ' \
'The wrap method returns a list of output lines. The returned list is empty if the wrapped output has no content'
wrapper = textwrap.TextWrapper(width=50)
word_list = wrapper.wrap(text=text)
for element in word_list:
print(element)
Code: Select all
This function wraps the input paragraph such that
each line in the paragraph is at most width
characters long. The wrap method returns a list of
output lines. The returned list is empty if the
wrapped output has no content
Code: Select all
import textwrap
value = """This function returns the answer as STRING and not LIST."""
wrapper = textwrap.TextWrapper(width=50)
string = wrapper.fill(text=value)
print (string)
Code: Select all
This function returns the answer as STRING and not
LIST.
Code: Select all
import textwrap
wrapper = textwrap.TextWrapper(width=50)
s = '''\
hello
world
'''
print(repr(s))
text = textwrap.dedent(s)
print(repr(text))
Code: Select all
'\\ \n hello \n world \n '
'\\ \n hello \n world \n'
อ้างอิง
https://docs.python.org/2/library/textwrap.html
https://www.geeksforgeeks.org/textwrap-text-wrapping-filling-python/
https://pymotw.com/3/textwrap/