Python 小抄


  • 类的写法

  • 用法:f"{year}"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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”

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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)