字符串split(),join()
1.split():以切割符切割,把切割的每一个元素放到一个列表中
#join() 把列表或元组中的元素通过某个字符拼接起来 name_list=['eugenia','18','nb'] name_str=",".join(name_list) print(name_str)
#求和1/1+1/3+1/5......+1/99 i=1 sum=0 num_list=[] while i<100: sum+=1/i num_list.append('1/{0}'.format(i)) i+=2 print(num_list) sum_str="+".join(num_list) sum_str=sum_str+"="+str(sum) print(sum_str)
模块
在任何一个py文件都是一个模块,py文件中的任何变量或者函数也属于一个模块
引用模块:使用import
比如导入内置模块
import os #os是内置模块
内置模块都是在python安装lib路径
例如本机是在 D:\python\lib
print(os.getcwd()) #等同于Linux的pwd
使用from...import
name_str=['a','b','c'] def test_code(x,y): print(x) pritn(y) from day01.test import name_str #day01是选取的pycharm中存在的Directtory文件 print(name_str)
from day01.test import test_code as tc
test_code(1,3) #未取别名
tc(1,3) #如果取别名的话,就使用别名
安装requests模块
import requests
get请求方法:
语法:
方法一:response=requests("get",url="api接口/过滤条件") 方法二:response=requests.get(url="api接口/过滤条件")
print(response.json())
#get请求方法一: response=requests.request("get",url="http://49.233.108.117:3000/api/v1/topics?limit=1&page=2") #topics?limit=1&page=2表示:在主题页面,指定第二页,返回数量为1 print(response.json()) #get请求方法二: #查看源码使用 按住ctrl+点击get response=requests.get(url="http://49.233.108.117:3000/api/v1/topics?limit=1&page=2")
print(response.json())
post请求方法
#新增一个主题的语法:
#自定义变量名={"key":"value",
#"key":"value",
......,
......,
"key":"value"
}
方法一:response=requests.request("post","url接口地址/页面位置",json=自定义变量名(必须同上) 方法二:response=requests.post("url接口地址/页面位置",json=自定义变量名(必须同上))
print(response.json()) #打印响应结果
新增一个主题
import requests new_topic_info={"accesstoken":"xxx", "titile":"python最后一天", "tab":"ask", "content":"python最后一天,天气真好!"} #请求方法一: response=requests.request("post","http://49.233.108.1117:3000/api/v1/topics",json=new_topic_info) #请求方法二: response=requests.post("http://49.233.108.1117:3000/api/v1/topics",json=new_topic_info)
#响应: print(response.json())
关联
获取新增主题之后的topic_id作为入参
更新主题
import requests
accesstoken="e046f8d4-551b-4f47-8168-4dadd9b1f1a7" url="http://49.233.108.117:3000/api/v1" #post请求创建一个新主题 new_topic_info = {"accesstoken":accesstoken, "title": "python最后一天", "tab": "ask", "content": "最后一天,伟哥居然没来。对,他放弃了"} response=requests.post("{0}/topics".format(url),json=new_topic_info) #运行post请求后获取到topic_id json_data=response.json() t_id=json_data.get("topic_id") #topic_id不存在则返回none json_data["topic_id"] #更新主题,新增主题后获取到的topic_id作为入参 if t_id is None: #None首字母必须大写,否则无法识别 print("新增主题发生错误") else: update_topic_info={"accesstoken":accesstoken, #accesstoken不是变量,不能加引号 "topic_id":t_id, #t_id不是变量,不能加引号 "title":"打发第三方士大夫第三方天气真好", "tab":"ask", "content":"坚实的离开房间观看价格"} response_obj=requests.post( "{0}/topics/update".format(url),json=update_topic_info) print(response_obj.json() )
浙公网安备 33010602011771号