美文网首页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日常小知识

    一:python列表中的所有值转换为字符串,以及列表拼接成一个字符串 二:字符串转换 三:创建文件并按行写入数据 ...

  • Python3.0中nonlocal关键字和python2.xl

    python 应用小知识,Python3.0中nonlocal关键字和python2.xlist或dict。希望小...

  • Python小知识

    Python的优点:功能强大,开发效率高,应用广泛,易上手,语法简洁 用途:网页开发,可视化(GUI)界面开发,网...

  • python小知识

    关于变量:python与其他编程语言稍有不同,他不是把值存储在变量中更像是把名字贴在变量上去。 python如何产...

  • python小知识

    函数的可变参数 *args: 接受普通参数,以元祖形式保存。**kwargs:接受关键字参数,以字典形式保存。更新...

  • python小知识

    本文主要记录python中常用的知识点,每一条都针对一个小问题给出可行的解决方法。 目录: 1.打印格式控制 2....

  • Python 小知识

    1. if name == 'main' 作用 简单来说,就是这个语句只有在这个文件自己被执行的时候才会true执...

  • python 小知识

    验证浮点数相加等于另外一个浮点数: 列表变为索引 元素 字符编码转换 生成当前时间唯一订单号 将多个列表按位置组合...

  • Python 这些不为人知的冷知识,你真正知道的有几个?

    谈谈 Python 那些不为人知的冷知识 小编在日常Code中遇到一些好玩,冷门的事情,通常都会记录下来。现在已经...

  • 日常育儿小知识

    1、退烧贴真的管用? 深秋季节,感冒流感、发烧等症状在宝宝身上尤为常见,一些娃儿又不听话,对感冒药拒绝拒绝再拒绝。...

网友评论

    本文标题:Python日常小知识

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