python的基础操作

字符串操作

查询

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

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
注意:如果字符串中含有除了字母或者数字之外的字符,比如空格,也会返回False

#判断字串中是否包含数字
string1="123ddddr.\.$$$"
pattern = re.compile('[0-9]+')
match = pattern.findall(string1)
print match    #结果为['123']

#判断字串x中是否包含datetime
from datetime import datetime
isinstance(x,datetime)
type(x) == datetime 
有时第二句不成功,因为type不考虑继承,而isinstance考虑继承

isdigit、isdecimal 和 s.isnumeric 区别

isdigit()
True: Unicode数字,byte数字(单字节),全角数字(双字节)
False: 汉字数字,罗马数字,小数
Error: 无

isdecimal()
True: Unicode数字,,全角数字(双字节)
False: 罗马数字,汉字数字,小数
Error: byte数字(单字节)

isnumeric()
True: Unicode 数字,全角数字(双字节),汉字数字
False: 小数,罗马数字
Error: byte数字(单字节)

str.isdecimal () 与str.isdigit()的区别
str.isdecimal() 函数只对十进制数返回 True,同时函数 str.isdigit() 对其他 unicode 支持的字符返回 True。
isalnum()必须是数字和字母的混合, isalpha()不区分大小写

查看字符串里是否有中文

def contain_chn(string):
    """
    原理: 中文字符的编码范围是:u4e00 - u9fff
    检查整个字符串是否包含中文
    :param string: 需要检查的字符串
    :return: bool
    """
    for ch in string:
        if u'u4e00' <= ch <= u'u9fff':
            return True
    return False

if  __name__ == "__main__":
    str1 = "刘亦菲123"
    print(str1,contain_chn(str1))
    ret2 = contain_chn("123.abd")
    str2 = "123.abd"
    print(str2,contain_chn(str2))

列表

新建列表

列表排序

list.sort方法

list.sort方法会就地排序列表,也就是说不会把原列表复制一份。这也是这个方法的返回值是None的原因,提醒:本方法不会新建一个列表。
在这种情况下返回None其实是Python的一个惯例:如果一个函数或者方法对对象进行的是就地改动,那它就应该返回 None,好让调用者知道传入的参数发生了变动,而且并未产生新的对象。

list_a = [1, 2, 8, 3, 7, 9, 5, 7]
# sort()方法没有返回值
list_b = list_a.sort()
print("list_a: ", list_a)
print('list_b: ', list_b)

list_a:  [1, 2, 3, 5, 7, 7, 8, 9]
list_b:  None

用返回None来表示就地改动这个惯例有个弊端,那就是调用者无法将其串联起来。而返回一个新对象的方法则正好相反,它们可以链式调用,从而形成连贯接口。

sorted内置函数

与 list.sort 相反,内置函数sorted会新建一个列表作为返回值。
这个方法可以接受任何形式的可迭代对象作为参数,甚至包括不可变序列或生成器,而不管sorted接受的是怎样的参数,它最后都会返回一个列表。

代码示例:

list_c = [1, 2, 8, 3, 7, 9, 5, 7]
# sorted内置函数会返回一个排序后的新列表
list_d = sorted(list_c)
print("list_c: ", list_c)
print('list_d: ', list_d)
运行结果:

list_c:  [1, 2, 8, 3, 7, 9, 5, 7]
list_d:  [1, 2, 3, 5, 7, 7, 8, 9]

可以看到,使用内置函数sorted时,返回了一个新的列表,而原列表没有发生改变。

这有两种好处:
1.如果我们即需要使用原列表,也需要使用排序后的列表,或者说我们要将一个非列表的可迭代对象排序成列表,sorted都可以做到
2.有返回值时,我们可以进行链式调用
可以对非列表的可迭代对象排序生成列表

str_e = 'python'
list_e = sorted(str_e)
print(list_e)
 
# 链式调用
str_f = '-'.join(sorted(str_e)).upper().split('-')
print(str_f)
运行结果:

['h', 'n', 'o', 'p', 't', 'y']
['H', 'N', 'O', 'P', 'T', 'Y']

关键字参数key和reverse

不管是 list.sort 方法还是 sorted 函数,都有两个可选的关键字参数:
key:接收一个只有一个参数的函数,这个函数会被用在序列里的每一个元素上,所产生的结果将是排序算法依赖的对比关键字。
比如说,在对一些字符串排序时,可以用 key=str.lower 来实现忽略大小写的排序,或者是用 key=len 进行基于字符串长度的排序。key的默认值是恒等函数,也就是默认用元素自己的值来排序。
reverse:如果被设定为 True,被排序的序列里的元素会以降序输出(也就是说把最大值当作最小值来排序),reverse的默认值是 False.

phone = ('HUAWEI', 'OPPO', 'MI', 'MEIZU', 'VIVO')
# 按长度进行排序
phone_list = sorted(phone, key=len)
print(phone_list)
 
phone_list_re = sorted(phone, key=len, reverse=True)
print(phone_list_re)
运行结果:

['MI', 'OPPO', 'VIVO', 'MEIZU', 'HUAWEI']
['HUAWEI', 'MEIZU', 'OPPO', 'VIVO', 'MI']

列表排序算法参考:https://blog.csdn.net/mrlevo520/article/details/77829204

列表插入

使用内置模块bisect插入

import bisect
a = [1, 2, 4, 5]
bisect.insort(a, 3)
print(a)
[1, 2, 3, 4, 5]

在列表中查找值,并返回指定index

list = [1,3,6,8,9,18]#先定义一个列表

def put_in(data,list,type):
    #参数依次为:data 要插入的数值,list 被插入的列表, type 无值匹配时获取的数据类型,up / down
    list0 = list.copy()
    for x in range(len(list)):
        if list0[x] == data:
            index = x
        else:
            import bisect
            bisect.insort(list0, data)
            index= list0.index(data)
            if type == 'up':
                index = index-1
            elif type == 'down':
                index = index+1
            elif type not in ['up','down']:
                index = index-1
        break
    return list0[index]

列表查询

从一个列表A中取出不在另一个列表B中的元素

问题场景:
要比较两个列表list_A、list_B,以便创建一个新列表,新列表中存储list_B中的元素没有出现在list_A中的内容。例如:

new_list=[]
list_A=["a", "b", "c", "d", "e"]
list_B=["b", "d", "f", "m"] 
结果应该是:

new_list=["f", "m"]

二、分析思路:

方案一:利用列表循环的方法,将list_B中的元素在list_A中进行循环查找,将不再列表list_A中的元素识别出来,这个方案的复杂度为O(n)。
new_list = [item for item in list_B if item not in list_A]

方案二:利用集合,将list_A转换成集合方式,然后在进行循环遍历,这个方案的复杂度为O(1)

new_list = [item for item in list_B if item not in set_A]

列表修改

I/O操作

读取TXT文件

读取 MySQL

Python 获取MySql某个表所有字段名

在使用python导出数据库中数据的时候,往往除了插入的数据以外,还有表字段等信息需要导出,查阅了资料后发现了2种方法
第一种:在mysql自带的表里查询,这个表保存了每张表的字段信息,可以用pymysql执行下面的sql语句

import pymysql
conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",db="study",autocommit=True)
cur = conn.cursor()
sql = "select COLUMN_NAME from information_schema.COLUMNS where table_name = 'userinfo'"
cur.execute(sql)
for field in cur.fetchall():
    print(field[0])
cur.close()
conn.close()

第二种:使用pymysql自带的方法获取#

import pymysql
conn = pymysql.connect(host="127.0.0.1",user="root",password="123456",db="study",autocommit=True)
cur = conn.cursor()
sql = "select * from userinfo"
result = cur.execute(sql)
desc = cur.description
for field in desc:
    print(field[0])
cur.close()
conn.close()
原文地址:https://www.cnblogs.com/treasury-manager/p/14755269.html