常用API
大小写
.lower() — 全部小写
.upper() — 全部大写
.title() — 各个字符的首字母大写
.capitalize() — 首字母大写
1 2 3 4
| name = input() print(name.lower()) print(name.upper()) print(name.title())
|
去除空格
.strip() — 删除两边空格
.lstrip() — 删除左边空格
.rstrip() — 删除右边空格
.replace(“ “,””) — 删除所有空格
.split() — 先切分,””.join() — 再拼接
不用循环语句的重复输出
使用*可以重复输出这段字符串
截取字符串前 10 个字符
list 列表的添加和移除
1 2 3 4 5 6 7 8 9
| offer_list = ['Allen', 'Tom'] for i in offer_list: print('{}, you have passed our interview and will soon become a member of our company.'.format(i))
offer_list.remove('Tom') offer_list.append('Andy')
for i in offer_list: print('{}, welcome to join us!'.format(i))
|
slice 切片函数
1 2 3 4 5
| group_list = [ 'Tom', 'Allen', 'Jane', 'William', 'Tony' ]
print(group_list[slice(0, 2)]) print(group_list[slice(1, 4)]) print(group_list[slice(3, 5)])
|
与或非
1 2 3 4 5 6 7
| x, y = input().split()
print(x and y) print(x or y) print(not int(x)) print(not int(y))
|
成员与列表 in
1 2 3 4
| line = input().split() name = input()
print(name in line)
|
保存数据到文件
两种保存的方式
1 2 3 4 5
| # fp = open('douban.json', 'w', encoding='utf-8') # fp.write(content)
with open('douban1.json', 'w', encoding='utf-8') as fp: fp.write(content)
|
https://www.zhihu.com/question/56927648
for循环
1 2
| for i in range(1, 6): print(i)
|
输出1-5,不包含6
function函数
定义函数使用def关键字
1 2 3 4 5 6 7
| def my_abs(x): if x >= 0: return x else: return -x
print(my_abs(-99))
|
定义空函数
定义main函数
1 2
| if __name__ == "__main__": main()
|
requests的基本使用
1 2 3 4
| response = requests.get(url=url, params=params, cookies=cookies, headers=headers)
content = response.content.decode('utf-8')
|
json的转换
content转换完毕之后可能需要再转成json对象,使用 json.loads
函数进行转换成dict对象
1 2 3 4 5 6 7 8 9
|
content = '{"status": "1", "state": "success", "data": [{"value": 7642}, {"value": 5199}, {"value": 4247}, {"value": 4604}, {"value": 3344}, {"value": 9769}, {"value": 6655}, {"value": 1263}, {"value": 3209}, {"value": 5533}]}' print(content) obj = json.loads(content) data_list = obj['data'] for d in data_list: value = d['value'] print(value)
|