美文网首页python
Python日常小知识

Python日常小知识

作者: 哈喽小生 | 来源:发表于2019-05-10 17:58 被阅读0次

    一:python列表中的所有值转换为字符串,以及列表拼接成一个字符串

    > ls1 = ['a', 1, 'b', 2] 
    > ls2 = [str(i) for i in ls1]
    > ls2 ['a', '1', 'b', '2'] 
    >ls3 = ''.join(ls2) 
    > ls3 'a1b2'
    

    二:字符串转换

    #字符串转为元组,返回:(1, 2, 3)
    print tuple(eval("(1,2,3)"))
    #字符串转为列表,返回:[1, 2, 3]
    print list(eval("(1,2,3)"))
    #字符串转为字典,返回:<type 'dict'>
    print type(eval("{'name':'ljq', 'age':24}"))
    

    三:创建文件并按行写入数据

    with open("%s\sitemap%d.txt" % (self.path,file_num), "a") as f:
        for i in url_list:
            u  = str(i) + '\n'
            f.writelines(u)
        f.close()
    

    四:Python调用API接口的几种方式

    方式一:
    import urllib2, urllib
    github_url = 'https://api.github.com/user/repos'
    password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_manager.add_password(None, github_url, 'user', '***')
    auth = urllib2.HTTPBasicAuthHandler(password_manager) # create an authentication handler
    opener = urllib2.build_opener(auth) # create an opener with the authentication handler
    urllib2.install_opener(opener) # install the opener...
    request = urllib2.Request(github_url, urllib.urlencode({'name':'Test repo', 'description': 'Some test repository'})) # Manual encoding required
    handler = urllib2.urlopen(request)
    print handler.read()
    
    方式二:
    import urllib, httplib2
    github_url = ""
    h = httplib2.Http(".cache")
    h.add_credentials("user", "******")
    data = urllib.urlencode({"name":"test"})
    resp, content = h.request(github_url, "POST", data)
    print content
    
    方式三:
    import pycurl, json
    github_url = ""
    user_pwd = "user:*****"
    data = json.dumps({"name": "test_repo", "description": "Some test repo"})
    c = pycurl.Curl()
    c.setopt(pycurl.URL, github_url)
    c.setopt(pycurl.USERPWD, user_pwd)
    c.setopt(pycurl.POST, 1)
    c.setopt(pycurl.POSTFIELDS, data)
    c.perform()
    
    方式四:
    import requests, json
    github_url =""
    data = json.dumps({'name':'test', 'description':'some test repo'})
    r = requests.post(github_url, data, auth=('user', '*****'))
    print r.json
    以上几种方式都可以调用API来执行动作,但requests这种方式代码最简洁,最清晰,建议采用。
    
    例子:
    import requests
    reqs = requests.session()
    reqs.keep_alive = False
    import json
    url = "http://127.0.0.1:9999/download/login" #接口地址
    data = {"user": "****", "password": "*****"}
    r = requests.post(url, data=data)
    print r.text
    print type(r.text)
    print json.loads(r.text)["user_id"]  
    

    五:将list列表里的数据按行写入到txt文件

    with open(file_num, "w") as f:
        for ip in url_list:
            f.write(ip)
            f.write('\n')
        f.close()
    

    六:Python判断字符串是否为字母或者数字

    严格解析:有除了数字或者字母外的符号(空格,分号,etc.)都会False
    isalnum()必须是数字和字母的混合
    isalpha()不区分大小写
    str_1 = "123"
    str_2 = "Abc"
    str_3 = "123Abc"
    
    #用isdigit函数判断是否数字
    print(str_1.isdigit())
    Ture
    print(str_2.isdigit())
    False
    print(str_3.isdigit())
    False
    
    #用isalpha判断是否字母
    print(str_1.isalpha())    
    False
    print(str_2.isalpha())
    Ture    
    print(str_3.isalpha())    
    False
    
    #isalnum判断是否数字和字母的组合
    print(str_1.isalnum())    
    Ture
    print(str_2.isalnum())
    Ture
    print(str_1.isalnum())    
    Ture
    

    未完待续。。。

    (欢迎加入Python交流群:930353061。人生苦短,我用python!!!)

    相关文章

      网友评论

        本文标题:Python日常小知识

        本文链接:https://www.haomeiwen.com/subject/offzoqtx.html