Huaiyao Jin

Huaiyao Jin

Python 小抄

- doctest

def divide_exact(n, d):
    """
    >>> q, r = divide_exact(2013, 10)
    >>> q
    201
    >>> r
    3
    """
    return n // d, n % d


jinhuaiyao@JinHuaiyaos-MacBook-Pro hw01 % python3 -m doctest -v test.py
Trying:
    q, r = divide_exact(2013, 10)
Expecting nothing
ok
Trying:
    q
Expecting:
    201
ok
Trying:
    r
Expecting:
    3
ok
1 items had no tests:
    test
1 items passed all tests:
   3 tests in test.divide_exact
3 tests in 2 items.
3 passed and 0 failed.
Test passed.

- [::-1]的用法

{w for w in words if len(w) == 6 and w[::-1] in words} 

该代码中的 w[::-1] 表示一个字符串 w 的反向字符串
也就是说它会将 w 中的字符从后往前倒序排列得到一个新的字符串
例如如果 w  "hello"那么 w[::-1] 就是 "olleh"

- 赋值方式
- 值交换

>>> x, y = 3, 4.5
>>> y, x = x, y
>>> x
4.5
>>> y
3

- 类的写法
- 用法f"{year}"

class Car:

    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year
        self.odometer_reading = 0

    def get_desc_name(self):
        long_name = f"{self.year} {self.make} {self.model}"
        return long_name.title()

- 文件内容写到列表
- zfill字符串右对齐前面填充0
- 用法"if birthday in pi_str"

filename = 'pi_million_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_str = ''
for line in lines:
    pi_str += line.strip()

for i in range(1, 32):
    birthday = '1805'
    birthday = birthday + str(i).zfill(2)

    if birthday in pi_str:
        print(f"{birthday} - yes")
    else:
        print(birthday)

- json的用法
- 用法ensure_ascii=False

import json

def count_words(filename):
    try:
        with open(filename, encoding='utf-8') as f:
            contents = f.read()
    except FileNotFoundError:
        print(f"Sorry, the file {filename} does not exist.")
    else:
        words = contents.split()
        num_words = len(words)
        return words[:10]

filename = 'alice.txt'

save_file = 'json.txt'
with open(save_file, 'w', encoding='utf-8') as f:
    json.dump(count_words(filename), f, ensure_ascii=False)
Python