Python 基础知识点

2018年07月15日

string

1name = "li qiang"
2name.title() => "Li Qiang"
3name.upper()
4name.lower()
5
6name.strip()
7name.rstrip()
8name.lstrip()

number

1# number to string
2age = 23
3str(age) => "23"
4
5int('23') => 23

list

 1a = [1, 2, 3]
 2a.append(4)
 3
 4a.insert(0, 0)
 5
 6del a[0]
 7
 8b = a.pop()
 9b = a.pop(0)
10
11# 删除值
12a.remove(3)
13
14a.sort()
15a.sort(reverse=True)
16
17b = sorted(a)
18b = sorted(a, reverse=True)
19
20a.reverse()
21
22len(a)
23
24
25for i in a:
26    print(i)
27
28for i in range(1, 5):
29    print(i)
30
31a = list(range(10))
32
33max(a)
34min(a)
35sum(a)
36
37# 列表解析
38b = [i*2 for i in a]
39
40# 切片
41b = a[0:3]
42b = a[:3]
43b = a[2:]
44b = a[-3:]
45# 复制列表
46b = a[:]
47
48# 集合
49set(a)

元组

1a = (100, 50)

字典

 1a = { 'name': 'lq', 'age': 24 }
 2a['name']
 3a['age']
 4
 5del a['age']
 6
 7for key, value in a.items():
 8    print(key, value)
 9
10for key in a:
11    print(key)
12
13for key in a.keys():
14    print(key)
15
16for value in a.values():
17    print(value)

用户输入

1msg = input('please input something')

function

 1# 接受任意数量的参数
 2# args 元组
 3def func(*args):
 4    for i in args:
 5        print(i)
 6
 7# 关键词实参
 8def build_profile(first, last, **user_info):
 9    do something
10
11**user_info 字典

file

 1# read
 2with open('1.txt') as x:
 3    contents = x.read()
 4    print(contents)
 5
 6# read line
 7with open('1.txt') as x:
 8    for line in x:
 9        print(line)
10
11# write
12with open('1.txt', 'w') as x:
13    x.write('hello world\n')
14
15# json dump
16import json
17a = [1, 2, 3]
18while open('1.txt', 'w') as x:
19    json.dump(a, x)
20
21# json load
22import json
23while open('1.txt') as x:
24    c = json.load(x)