阅读本文大概需要 10 分钟。
提要
哈喽,大家好!继续分享我整理的一些Python3笔记。
TL;DR
* 字符串基础
* 列表、字典、元组
* 文件
s = "hello webj2eedev."
s[0] = "W"
s = "abc\n\tefg"
print(s, len(s))
p = r'c:\name1\name2'
q = 'c:\name1\name2'
print(p)
print(q)
p = """
<html>
<body>
<h1>Hello Webj2eedev.</h1>
<body>
</html>
"""
print(p)
s = 'Hello Webj2eedev.'
r1 = s[:] # 复制
r2 = s[:5] # 切片
r3 = s[::-1] # 步长可以为负值
print(r1)
print(r2)
print(r3)
print(ord('W'))
print(chr(87))
print(ord("我"))
print(chr(25105))
a = ["hello", "world", "!"]
print(",".join(a))
# 所有类型,都可以用 %s
s = '%s --- %s --- %s --- %s' % ('abc', 3.1415, {"xm": "张三"}, [1, 2, 3])
print(s)
# 高级特性
print('---%-8.3f---' % (3.1415))
print('---%08.3f---' % (3.1415))
print('---%08d---' % (3.1415))
# 支持字典形式
print('---%(pi)-8.3f---' % {"pi": 3.1415})
print('----{0}---{1}---{2}---'.format('张三', '李四', '王五'))
print('----{zs}---{ls}---{ww}---'.format(zs='张三', ls='李四', ww='王五'))
print('----{0}---{1}---{ww}---'.format('张三', '李四', ww='王五'))
print('----{}---{}---{}---'.format('张三', '李四', '王五'))
import sys
print('---{0.platform:<30}---'.format(sys))
print('---{0.platform:^30}---'.format(sys))
print('---{0.platform:>30}---'.format(sys))
print('---{0:^30,}---'.format(123456789))
# 列表基本操作
len([1,2,3,4])
[1,2] + [3,4]
[1, 2, 1, 2, 1, 2, 1, 2]
# 列表迭代
3 in [1,2,3]
for x in [1,2,3]:
print(x, end='')
# 列表推导
[c * 4 for c in [1,2,3]]
[c * 4 for c in '123']
L = [3, 11, 50, 30, 9, -1]
L[1] = 12
L[0:2] = [4, 12, 51]
L.reverse()
L.sort(reverse=True)
L.extend([-2, -4, -10])
L[5:] = []
del L[3:]
M = L[:]
L is M
D = {'spam': 2, 'eggs': 3, 'ham': 1}
len(D)
'ham' in D
D.keys()
D.values()
D.items()
del D['spam']
D = {}
D[99] = 'spam'
Matrix = {}
Matrix[(0, 0, 0, 0)] = 99
with open('myfile.txt', 'w', encoding='utf-8') as myfile:
myfile.write('hello world. 张三李四王五')
import json
with open('myfile.json', 'w', encoding='utf-8') as myfile:
D = {"xm": "张三", "age": 18}
myfile.write( json.dumps(D, ensure_ascii=False) )
with open('myfile.json', 'r', encoding='utf-8') as myfile:
D = json.load(myfile)
print(D)
参考:
《Python学习手册 原书第五版 上册》