python3 read(f)_笨方法学Python3 - 错题集1

编程老大难,第N次从零开始学Python

ex5-ex26

1.“格式字符串”

字符串真的非常方便。你将在这个练习中学习如何创建包含变量的字符串。把你需要的变量放在 {} 里面就可以把变量嵌入在字符串中。你还需要在字符串前面加上字母 f (代表 format),比如 f"Hello, {somevar}"。双引号前面的 f 是为了告诉 python3: “这个字符串需要被格式化,把这些变量放在那儿。”

例:

do_not = "don't"

fun = 'funny'

x = f"{do_not} think that joke is {fun}"

print(x)

print(f"he told that {x}")

print("he told that {}".format(x)) #{}里面不能有空格

#错题:

print("Okay, today you added {new_items}") [wrong, you missed f to format variable into this line.]

print(f"Okay, today you added {new_items}") or

print("Okay, today you added {}".format(new_items))

2. strftime vs. strptime

strftime('%Y-%m-%d') 格式化format一个时间字符串,转换为特定格式输出

strptime(day,'%Y-%m-%d') 按照特定时间格式将字符串转换(解析parse)为时间类型

3. 换行

end = ' ' 后面如果有内容,不换行

\n 换行 例子:months = "\nJan\nFeb \nMar \nApr \nMay \nJun"

4. String, Boolean, Int

单引号或者双引号都可以用来创建字符串吗?在 Python 里面,两个都可以,不过严格来讲,像a或者snow这种比较短的字符串应该用单引号。

Python 把True和False当成代表“对“和”错“的关键词,所以不加单引号/双引号。数字也不加单引号/双引号。

5. 三个双引号three double-quotes

You can jump to newline and write as much as you like.

6.

day1 = ("Mon", "Tue", "Wed", "Thur")

print("here is days: ", day1) # here is days: ('Mon', 'Tue', 'Wed', 'Thur')

day2 = ('Mon', 'Tue', 'Wed', 'Thur')

print("here is days: ", day2) # here is days: ('Mon', 'Tue', 'Wed', 'Thur')

day3 = ("Mon, Tue, Wed, Thur")

print("here is days: ", day3) # here is days: Mon, Tue, Wed, Thur #???

7. 转义

方法一:\ 这个字符可以把没法输入的字符转化成字符串。一个很重要的转义字符就是转义单引号或者双引号。

\t = tab(大空格)

\n = 换行

例子:

print("I am 6'1\" tall")

print('I am 6\'1" tall')

tabby_cat = "\tI'm tabbed in." # tab

persian_cat = "I'm split\non a line." # 换行

backslash_cat = "I'm \\ a \\ cat." # 转义\

python ex-18.py this\ is\ sample.txt #转义带空格的文件名

方法二:用三个双引号,即""",这样就能像字符串一样运行。""" 可换成 '''。

例子:

fat_cat = """

I'll do a list:

\t* Cat food

\t* Fishies

\t* Catnip \n\t* Grass"""

8. argv

这个argv是 “argument variable” ,一个在编程语言中非常标准的名字,你会在其它很多的语言中看到它的使用。当你运行 Python 脚本的时候,这个变量(variable)保存了你传给 Python 脚本的参数(argument)。

#argv only read filename in first variable

例子:

from sys import argv # import argv package in

script, first, second, third = argv # unpack argv and spilt into 4 variables(you can define the no. of variables here)

#python ex11.py 1st 2nd 3rd # run this command in CMD, argv expected 4 variables/ values to unpack here.

print("The script is called: ", script)

print("The first is called: ", first)

print("The second is called: ", second)

print("The third is called: ", third)

注意:导入sys模块,把argv feature引入脚本 (feature = modules = library)

9.argv和input()之间的区别

区别取决于用户在哪被要求输入,如果是在命令行,就用 argv。如果你想让它们在程序已经运行的情况下用键盘输入,那就用input()。

10.Python文档生成工具pydoc

D:\>python -m pydoc

D:\>python -m pydoc -p 1234 #比如说: 端口为1234 #pydoc server ready at http://localhost:1234/

11. open() & read() & input()

txt = filename.open() # wrong, str 'filename' doesnt have 'open' attr. should be txt = open(filename)

print(f"Here's your file {filename}")

print(txt.read()) # read file here, remember that read is a function函数 without 参数

error msg:

txt_again = input("Enter file name: ")

print(txt_again.read()) # wrong, str 'txt_again' doesnt have 'read' attr.

# must get the file name first, then open file, followed by read# filename, open, read

file_again = input("Enter file name: ")

txt_again = open(file_again)

print(txt_again.read())

12. python shell

开始-> 搜索python3.8 -> 打开python(cmd)

输入quit()并回车,退出。

在python shell打开和读取txt文档

filename = open('C:\\Users\\Administrator\\Python Practice\\ex15-sample.txt', 'r', encoding = 'utf-8') #斜线需要转义 #需要encoding

print(filename.read()) #不要忘记read文档

13. 获取文件名,input()和argv方法,哪种方法更好?如果需要读取的文件名里有空格,那么用argv时,cmd会认为文件名是两个参数,从而读取失败。

如果用input(),则多了一次脚本内的输入,更费时间。

14. 读写文件open -打开文件

close - 关闭文件,就像编辑器中的 “文件->另存为”一样。

read - 读取文件内容。你可以把读取结果赋给一个变量。

readline - 只读取文本文件的一行内容。

truncate - 清空文件。清空的时候要当心。[#truncate也是一种writing,所以在open文件时要赋予write的权利]

write('stuff') - 给文件写入一些“东西”。 [#write一次只取一个argument]

writelines - 给文件写入一个列表list

seek(0) - 把读/写的位置移到文件最开头。

'w','w+','r+'以及'a+'。这样会让文件以读和写的模式打开,取决于你用的是那个符号以及文件所在的位置等。

# 只读:

txt = open(filename)

print(txt.read())

读写(包括truncate)

txt = open(filename, 'w')

txt.truncate()

txt.write(line1)

15. 一次写入多行

print("I am writing your three lines...")

txt.writelines([line1, "\n", line2, "\n", line3, "\n"]) # 方法一,用List代替多行

txt.write(f"{line1}, '\n', {line2}, '\n', {line3}, '\n'") # 方法二,format the lines

16. exists()

from os.path import exists 检查文件是否存在,返回 True 或 False

print(f"Does the output file exist? {exists(to_file)}") True

17. 简化代码

in_file = open(from_file)

indata = in_file.read()

-> indata = open(from_file).read()

# 记得移除多余的in_file.close()

18. 函数

# this one like your scripts with argv

def print_two(*args):

arg1, arg2 = args # 解包这个参数arg

print(f"arg1: {arg1}, arg2: {arg2}")

*args中的*是什么作用?这是告诉 Python 取所有的参数给函数,然后把它们放在args里放成一列,很像你之前学的argv,只不过这个是为函数设置的。这种不常用,除非有特殊需要。

# that *args is actually pointless, we can just do this

def print_two_again(arg1, arg2):

print(f"arg1: {arg1}, arg2: {arg2}")

19. 函数 checklist (核查表):你是否用 def 来创建函数了?

你的函数名是只包含字符和 _ (下划线)吗?

你在函数名后面放 ( (左圆括号)了吗?

你在左圆括号后面放参数(argument)了吗?参数之间是以逗号隔开的吗?)

你的每个参数都是唯一的吗(即没有重名)?

你在参数后面放 ) (右圆括号)和 : (冒号)了吗?

你在与这个函数相关的代码行前面加上四个空格的缩进了吗?(不能多,也不能少)

你是通过另起一行不缩进来结束你的函数的吗?

当你运行(使用或者调用)一个函数时,检查以下事项:你是通过输入函数名称来运行/调用/使用一个函数的吗?

你运行的时候有在名称后面加 ( 吗?

你有把你想要的值放在圆括号里并用逗号隔开了吗?

你是以 ) 来结束调用这个函数的吗?

20. 用int()来把你通过input()获取的内容转化成数值。

print("And we can ask user input two values:")

value_1 = int(input("How much amount of cheese do you want?"))

value_2 = int(input("How many crackers do you want?"))

cheese_and_crackers(value_1, value_2)

float(input(xxxxx))可转化成浮点数

21. 一个函数里包含的参数有数量限制吗?这取决于 Python 的版本以及你的电脑,但是这个数量其实相当大。实践中一个函数包含 5 个参数为宜,再多就比较难用了。

22. 像amount_of_cheese这样的全局变量(global variables)尽量不要和函数变量同名

23.seek函数

seek()方法用于移动文件读取指针到指定位置。seek()函数处理的是字节(bytes),不是行。seek(0)这个代码把文件移动到 0 字节(也就是第一个字节处)。

def rewind(f): # rewind() 只是一个函数名(倒带)

f.seek(0) # 移动到文件最开始

24. readline()

readline() 是怎么知道每一行在哪儿的? readline() 里面的代码能够扫描文件的每个字节,当它发现一个 \n 字符,它就会停止扫描这个文件,然后回到它发现的地方。文件 f 就负责在每次调用 readline() 之后维持文件的当前位置,以此来保证它能阅读到每一行。

为什么文件中的行之间会有空行? readline() 函数返回文件中每行最后的 \n 。又在 print 函数的结尾加上一个 end = " " 来避免给每行加上两个 \n 。

def print_a_line(line_count, f):

print(line_count, f.readline()) #print out the 1st line

current_file = open(input_file)

current_line = 1

print_a_line(current_line, current_file)

25. python是从内而外运行的

26. txt write错题

# when txt open file without 'w', will receive error msg: 'str' object has no attribute 'write'

txt = open('lala.txt', 'w')

new_content = input("write something new...")

txt.write(new_content)

# or txt.write(f"{new_content}")

# or txt.writelines([new_content, "\n", "dont let him look down at you"])

txt.close()

27. encoding错误

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd1 in position 8: invalid continuation byte

错误:文件出现utf-8无法编译的内容,需要使用一种encoding来使文件能够被正常读取。

languages = open("languages.txt", encoding = "utf-8") 将utf-8换成 unicode_escape

28. strip()

移除字符串头尾指定的字符(默认为空格或换行符)或字符序

29.DBES:Decode Bytes Encode Strings”(解码字节,编码字符串)

raw_bytes = next_lang.encode(encoding, errors = errors)

cooked_string = raw_bytes.decode(encoding, errors = errors)用.decode(惯例)来获取字符串

b'Arpetan'[raw bytes] <===> Arpetan [cooked string]

DBES” 这个记忆符号,它代表“Decode Bytes Encode Strings”(解码字节,编码字符串)

30. bits,byte,字符

一个byte字节是 8 个bit比特(0 / 1)

“字节“ 即bytes

“字符”指计算机中使用的文字和符号,比如1、2、3、A、B、C、~!·#¥%……—*()——+、等等。

用惯例(如ASCII 码)来让数字映射(map)成文字

ASCII 惯例来用 8 个比特给一个字母编码;Unicode惯例用 32 个比特来编码一个字符(一个 32 位比特的数字意味着我们可以存储 4,294,967,295 个字符(2^32)

压缩(compression)编码惯例:用 8 个比特来编码大多数通用字符,然后当我们需要编码更多字符的时候再使用更多的数字。

在 Python 中编码文本的惯例叫做“utf-8”,即“Unicode Transformation Format 8 Bits”,它是一个把 Unicode 字符编码成字节序列的惯例。

8 bits ------ python ex23.py "utf-8" 'strict'

b'' <===>

b'Aragon\xc3\x83\xc2\x83\xc3\x82\xc2\xa9s' <===> Aragonés

b'Arpetan' <===> Arpetan

16 bits ------ python ex23.py "utf-16" 'strict'

b'\xff\xfe' <===>

b'\xff\xfeA\x00r\x00a\x00g\x00o\x00n\x00\xc3\x00\x83\x00\xc2\x00\xa9\x00s\x00' <===> Aragonés

b'\xff\xfeA\x00r\x00p\x00e\x00t\x00a\x00n\x00' <===> Arpetan

32 bits ----- python ex23.py "utf-32" 'strict'

b'\xff\xfe\x00\x00' <===>

b'\xff\xfe\x00\x00A\x00\x00\x00r\x00\x00\x00a\x00\x00\x00g\x00\x00\x00o\x00\x00\x00n\x00\x00\x00\xc3\x00\x00\x00\x83\x00\x00\x00\xc2\x00\x00\x00\xa9\x00\x00\x00s\x00\x00\x00' <===> Aragonés

b'\xff\xfe\x00\x00A\x00\x00\x00r\x00\x00\x00p\x00\x00\x00e\x00\x00\x00t\x00\x00\x00a\x00\x00\x00n\x00\x00\x00' <===> Arpetan

相比16/ 32bits,用8bits更节省空间

big5 ------ python ex23.py big5 replace

LookupError: unknown encoding: utf-4

31. *formula

formula = secret_formula(start_point)

print("We'd have {} beans, {} jars, {} crates.".format(*formula))

*formula中的*是什么作用?这是告诉 Python 取所有的参数给函数,然后把它们放在formula里放成一列

*formula = beans, jars, crates

32. pop()

返回从列表中移除的对象。

pop(0) 返回从列表中移除的第一个元素对象。

33. help() & quit()

After enter python interpreter mode(by enter python in cmd), execute ex25.py (see below) and key in help(ex25) in CMD, the the file name, functions & their comments and file path will be shown; or key in help(ex25.break_words) to show the comment of certain function.

Enterquit()to exit interpreter mode.

>>> import ex25 ---- 可以用from ex25 import *代替

>>> sentence = "All good things come to those who wait."

>>> words = ex25.break_words(sentence)

>>> words

['All', 'good', 'things', 'come', 'to', 'those', 'who', 'wait.']

>>> ex25.print_first_word(words)

All

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值