View Categories

11.1. تنسيق المخرجات

1 دقيقة

جدول المحتويات

11.1. تنسيق المخرجات #

تغطي هذه الجولة الثانية وحدات أكثر تقدمًا تلبي احتياجات البرمجة الاحترافية. نادرًا ما تُستخدم هذه الوحدات في نصوص برمجية صغيرة. والبداية مع تنسيق المخرجات .

توفر وحدة reprlib إصدارًا من دالة repr() مُخصصًا للعروض المختصرة للحاويات الكبيرة أو المتداخلة:

>>> import reprlib
>>> reprlib.repr(set('supercalifragilisticexpialidocious'))
"{'a', 'c', 'd', 'e', 'f', 'g', ...}"

توفر وحدة pprint تحكمًا أكثر تطورًا في طباعة كلٍّ من الكائنات المُدمجة والمُعرّفة من قِبَل المستخدم بطريقة يسهل على المُفسّر قراءتها. عندما تكون النتيجة أطول من سطر واحد، تُضيف “الطابعة الجميلة” فواصل أسطر ومسافات بادئة لإظهار بنية البيانات بشكل أوضح:

>>> import pprint
>>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta',
...     'yellow'], 'blue']]]
...
>>> pprint.pprint(t, width=30)
[[[['black', 'cyan'],
   'white',
   ['green', 'red']],
  [['magenta', 'yellow'],
   'blue']]]

تُنسّق وحدة textwrap فقرات النص لتناسب عرض شاشة مُحدد:

>>> import textwrap
>>> doc = """The wrap() method is just like fill() except that it returns
... a list of strings instead of one big string with newlines to separate
... the wrapped lines."""
...
>>> print(textwrap.fill(doc, width=40))
The wrap() method is just like fill()
except that it returns a list of strings
instead of one big string with newlines
to separate the wrapped lines.

تتصل وحدة locale بقاعدة بيانات بتنسيقات بيانات خاصة بالثقافة. توفر سمة التجميع في دالة تنسيق الإعدادات المحلية طريقة مباشرة لتنسيق الأرقام باستخدام فواصل المجموعات:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'English_United States.1252')
'English_United States.1252'
>>> conv = locale.localeconv()          # get a mapping of conventions
>>> x = 1234567.8
>>> locale.format("%d", x, grouping=True)
'1,234,567'
>>> locale.format_string("%s%.*f", (conv['currency_symbol'],
...                      conv['frac_digits'], x), grouping=True)
'$1,234,567.80'
error: Content is protected !!
Scroll to Top