Skip to content

Reading Notes: Python 3 Module of the Week

Website

Topics

1. Text (string, textwrap, re, difflib)

  1. Don't really understand the power of string.Template()
  2. t = string.Template() works with t.substitute(value)
  3. textwrap seems to be useful in formatting lines
    • textwrap.fill(text, width = w)
    • textwrap.dedent(text) removes the existing indentation, but not fully dedent every line -- similar to Ctrl + [
    • textwrap.indent(text, prefix_string, predicate = fn) can add some prefix_string at the beginning of each line, predicate function returns True/False to decide whether you need indent
    • we can also do handing indent textwrap.fill(dedented_text, initial_indent='', subsequent_indent=' ' * 4, width=50,))
    • textwrap.shorten(text, length) can shorten/truncate a text
  4. difflib can diff two texts 【值得多了解】
    • d = difflib.Differ()
    • diff = d.compare(text_1, text_2)
    • ndiff() ignores space and tab characters
    • difflib.SequenceMatcher can match (e.g. SequenceMatcher.find_longest_match()) and change one string to another with modification (e.g.SequenceMatcher.get_opcodes())
  5. re is a monster 【等待阅读】

2. Date & Time (time, datetime, calendar)

  1. time 【等待阅读】
  2. datetime 【等待阅读】
  3. calendar is good for date in a Week
    • c = calendar.TextCalendar(calendar.SUNDAY) configures a calendar starts with SUNDAY. We can use c.prmonth(2017, 7) to print the pre-formatted calendar
    • c = calendar.HTMLCalendar(calendar.SUNDAY) and c.formatmonth() achieves similar results with HTML/CSS wrapping
    • get some locales (U.S., French, China, etc). c = calendar.LocaleTextCalendar(locale='en_US') and c.prmonth(2017, 7) now will gives different date label (Mo/Tu/We or Lu/Ma/Me...)
    • c = calendar.monthcalendar(year, month) returns a week-row list of the month, [[week1], [week2], ...] with [week1] as something like [0,0,0,0,0,1,2], we can use something like calendar.THURSDAY to see the actual day, such as c[0][calendar.FRIDAY] is to get the day of the first Friday in the month; Return 0 mean that day doesn't exist.