类型转换、字符串处理、正则、异常处理

 

1.类型转换:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#_______________________________str转list__________________________________________________
#########强制转换-不推荐
str1 = "12345"
list1 = list(str1)
print(list1)

#########split切割转换-推荐
str2 = "123d sjhid dhi"
##默认以空格分割,也可指定符号或字母
list2 = str2.split() #or list2 = str2.split(" ")
#list2 = str2.split('d')#指定字母分割
print (list2)

#_______________________________list转str___________________________________________________ list3=['chen','wei','25','popp123','hjdh'] ####默认list转到str-推荐 # str4 = "".join(list3) # print (str4) # ####每个元素用.隔开 # str5 = ".".join(list3) # print (str5) # ####每个元素用空格隔开 str6 = " ".join(list3) print(str6) #########list转str import json promotion_ids_list=["123","chenwei"] #把list转成str promotion_ids = json.dumps(promotion_ids_list) print(type(promotion_ids)) #使用str也可以把list转成str aa=str(promotion_ids) print(type(aa))
#________________________________list转dict_________________________________________________ ####两个list转dict list1 = ['key1','key2','key3'] list2 = ['1','2','3'] print(dict(zip(list1,list2))) ####将嵌套list转为dict-方式1 new_list= [['key1','value1'],['key2','value2'],['key3','value3']] print(dict(new_list)) ####将嵌套list转为dict-方式2 new_list= [['key1','value1'],['key2','value2'],['key3','value3']] new_dict = {} for i in new_list: new_dict[i[0]] = i[1] #i也是一个字典 print(new_dict)
#________________________________dict转list_____________________________________________________ ###把一个字典拆成一个list或两个list或嵌套list d={1:"a",2:"b",3:"c"} result=[]#存放key和value的list res=[] ree=[]#嵌套list for key,value in d.items(): res.append(key)#把key追加到res result.extend([key,value])#把key,value同时追加到result() ree.append([key,value])#把key追加到res print('result:',result) print('res:',res) print('ree:',ree) ###dict转list-方式二 d1={1:"a",2:"b",3:"c"} #list_keys= [ i for i in d1.keys()]#把key转成list list_values = [i for i in d1.values()]#把valus转成list print(list_values) ###dict转list-方式三 a = {'a' : 1, 'b': 2, 'c' : 3} #字典中的key转换为列表 key_value = list(a.keys())#也可以values() print('字典中的key转换为列表:', key_value) #________________________dict转str_____________________________________________________________ import json b = {'a' : 1, 'b': 2, 'c' : 3} bb=json.dumps(b) print(type(bb)) print(bb) #__________________________str转dict___________________________________________________________ b1='{"a": 1, "b": 2, "c": 3}' ####通过loads print(type(b1)) b11=json.loads(b1) print(type(b11)) ###通过eval b22=eval(b1) print(type(b22)) print(b22) #___________________________ bytes和str相互转换___________________________________________________ # bytes对象 b = b"example" # str对象 s = "example" #方式一 # str 转 bytes sb = bytes(s, encoding = "utf8") print(sb) # bytes 转 str bs = str(b, encoding = "utf8") print(bs) # 方式二 # str 转 bytes sb2 = str.encode(s) print(sb2) # bytes 转 str bs2 = bytes.decode(b) print(bs2)

 

2.正则匹配:

#!/usr/bin/env python
# encoding: utf-8
import re

###_________________________________________findall表达式________________________________________________
'''
findall:在字符串中找到正则表达式所匹配的所有子串,并返回一个列表,如果没有找到匹配的,则返回空列表
'''
def chen():
    a=12
    b='20'
    ff=['5','99','dd']
    e='heheh123'
    dd="chen123.ll"
    d=5
    print("函数内部")
    rr=re.findall(r"eh(.+)",e)
    print(rr)
a=chen()

###匹配字符串中数字
a='九州379服'
aa=re.findall(r'\d+',a)#从we匹配
print(aa)
print(aa[0])

####匹配we开始的字符
bb=re.findall('we(.*)','d*T#we12345678')#从we匹配
print(bb)
###字母
bb1=re.findall(r'[A-Za-z]+','d*T#we12345678')#从we匹配
print(bb1)

#####区间匹配
text = "Find all matches in this text"
matches = re.findall(r'\ball (.*?) this\b', text)
print("指定开头结尾匹配中间数据:",matches)
matches = re.findall(r'\bma\w+', text)
print("匹配开头ma结尾为数字字母下划线:",matches)


###匹配wifi名称
aa='''
  iface=wlan0 ident=[{type=WIFI, subType=COMBINED, networkId=Dalan_guest22}]

  iface=wlan0 ident=[{type=WIFI, subType=COMBINED, networkId=Dalan_guest}]

  ident=[{type=WIFI, subType=COMBINED, networkId=Dalan_guest}] uid=-1 set=ALL tag=0x0

  ident=[{type=WIFI, subType=COMBINED, networkId=Dalan_guest}] uid=-1 set=ALL tag=0x0
'''
text=re.findall('networkId=(.*)}',aa)#从networkId=匹配到 }结束
print(text)


#____________________________________sub表达式________________________________________________________
'''
sub:过滤匹配到的字符串
'''
a=re.sub(r'\d', "", "abc34*%d")#过滤匹配到的字符串
b=re.sub(r'\d', "adc", "abc34*%d")#用adc替换匹配的字符
print(b)

phone = "2004-959-559 # 这是一个电话号码"
# 删除注释
num = re.sub(r'#.*$', "", phone)
print ("电话号码 : ", num)

# 移除非数字的内容
num = re.sub(r'\D', "", phone)
print ("电话号码 : ", num)

#_____________________________________________match_____________________________________________
'''
match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回None。
re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None
'''

print(re.match(r'^www', 'www.baidu.com').span())#匹配www,在起始位置匹配
print(re.match(r'^ww', 'www.baidu.com').span())#匹配ww,在起始位置匹配
print(re.match(r'^www', 'www.baidu.com'))#匹配www,# 不在起始位置匹配

print(re.match("\d{1,3}","10086"))#匹配100
print(re.match("\D{1,3}","10086"))#匹配失败了
aa=re.match("\D{1,4}","chenwei10086")#匹配chen
print(aa)
#打印匹配结果
print('111',aa.group())
print(aa[0])

###match匹配url前缀
apk_link="http://file.superdalan.com/6cf5700f1a8e"
apk=re.match(r'^https?:/{2}file.superdalan.com.+$', apk_link)
print(apk.group(0))
#注意:?可以匹配0次,及向左移位一次(可匹配http及https)


#________________________________________________search表达式_____________________________________________________
'''
# re.match与re.search的区别:re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
'''
###可以匹配成功的
res = re.search("python","Life is short. I learn python!")
print(res)
print(res.group())#匹配表达式
print(res.string)   #匹配字符串

###匹配失败的
res = re.search("java","Life is short. I learn python!")
print(res)

###输出匹配位置和原配字符串
res = re.search("python","Life is short. I learn python!")
print(res.start())  #匹配字符串的开始位置
print(res.end())    #匹配字符串的结束位置
print(res.span())   #匹配字符串的元组(开始位置+结束位置)
print(res.string)   #匹配字符串

###search匹配案例
str = 'response body:{"name":"张三","age":20,"Idcard_no":"4100058971","phone":"15011100001"}'
res = re.search("{.*?}",str)  #万能的.*?
print(res)
print(res.group()) #或者print(res[0])

###search匹配案例2
import re
aa="""__GetZoneResult_ = {
        mts:'1597557',
    province:'广东',
    catName:'中国移动',
    telString:'15975579874',
    carrier:'广东移动'
    }"""
match = re.search(r"province:'(.*?)'", aa)
carrier = match.group(1)
res =  carrier if carrier  else "未找到匹配的结果"
print(res)

 

3.遍历字符串的4中方式:

girl_str = "love You"

# ##通过for in的方式
for i in girl_str:
    print(i)


# ##内置函数iter()遍历
for every_char in iter(girl_str):
    print(every_char)


##内置函数enumerate()遍历
for index, every_char in enumerate(girl_str):
    #print(str(index) + every_char)
    #print(every_char)
    print(str(every_char))


#通过range遍历
for i in range(len(girl_str)):
    print(girl_str[i])

 

4.字符串判断&包含&为空:

# __________________判断字符串值是否相等_______________
if string1 == string2:
    print("字符串值相等")
else:
    print("字符串值不相等")

# ___________________判断字符串长度____________________
if len(string1) > len(string2):
    print("string1个数,大于string2")
elif len(string1) < len(string2):
    print("string1个数,小于string2")
else:
    print("string1个数,等于string2个数")

# ____________________字符串包含______________________
if "He" in string1:
    print("string1包含He")

# 查找字符串并返回位置,没找到就返回-1
print(string1.find("llo"))

# 魔法方法判断字符串包含xx字符,返回Ture或False
print(string1.__contains__("llo"))

# 正则方式判断字符串包含xx字符,返回Ture或False
import operator

print(operator.contains("hellopython", "llo"))


#_______________________字符串为空判断__________________________________
aa="";
#方法一
if not aa:
    print("字符串为空1")
#方法二
if len(aa)<=0:
    print("字符串为空2")
#方法三
print(bool(aa))

#检测字符串是否只由空格组成
print(aa.isspace())

#去两边空格str.strip()

#去左空格:str.lstrip()

#去右空格:str.rstrip()

 

 5.异常处理:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

##_____________________________________try与except和else执行顺序________________________________________
try:
      print('正常执行'+'333')
except:
      print('异常时执行')
else:
      print('语句异常后不执行')#else和try一起的



###_______________________________try与except和finally执行顺序___________________________________________
try:
      print(111111111)
except:
      print('异常时执行')
finally:
      print('无论语句是否异常都会执行')



####__________________________________函数:一个try对应多个 except_______________________________________________
def all(sstr):
      try:
            if  sstr=='chenwei':
                  print('正常执行:'+sstr)
            elif sstr==520:
                  print('正常执行:'+sstr)

            elif sstr == '大蓝游戏':
                  sstr=int(sstr)
            elif sstr == 'test':
                  print(aa)#引用未定义的变量aa,故意引发异常
            elif sstr ==100:
                print(len())

      except TypeError:
            print('数据类型异常')
      except ValueError:
            print('数据值错误')
      except:
            print('默认异常-如果上面异常不存在就报此异常')
      else:
            print('语句异常后不执行')#else和try一起的

#all('chenwei')#正常的
#all(520)#数据类型异常
all('大蓝游戏')#数据值错误
all('test')#定义的异常类没有捕获到,就走默认异常



##________________________________________一个try对应多个 except___________________________________________________
chen='testeee'
try:
    if  chen=='chen123':
          print('正常执行:'+sstr)#变量未定义,,故意引发异常)
    elif chen == 'test':
          print(chen+555)#数据类型异常
    elif chen !=100:
        print('1111')
        print(chen.sort())#没有捕获到就显示万能异常

except ValueError:
    print('数据值错误')
except NameError:
    print('变量类型错误')
except:
    print('万能异常')



##________________________________________一个try对应多个 except___________________________________________________
chen = 'test'
chen1 = 'chen123'
chen2=['dalan','test','123']
chen3={'name':'dalan_ganme','age':'105'}

try:
    #print('正常执行:' + sstr)  # 变量未定义,,故意引发异常)
    #索引错误
    #print(chen[5]) #序列中没有此索引、越界错误
    #print(chen1[10]) #没有此索引、越界错误
    #key错误
    print(chen3['test']) #打印不存在的key

except ValueError:
    print('数据值错误')
except NameError:
    print('变量类型错误')
 
except KeyError as e:
    print('捕获到一个Key值错误:',e)
  
except IndexError as e:
    print('捕获一个索引值错误')

except TypeError:
    print('对类型无效的操作')

except:
    print('万能异常')


###____________________________________自定义异常自定义类型__________________________________________________________
#自定义异常类型必须继承Exception___
class chen_error(Exception):#注意:自定异常类型必须继承Exception
    def __init__(self,name):
        self.name=name

    def chen(self,age):
        print(age)
        try:
            if age > 20:
                raise chen_error("自定义异常")
            else:
                print(self.name)
        except chen_error as e:
            print(e)#打印异常
ddd=chen_error('chenwei')
ddd.chen(52)



###___________________________________________自定义异常raise________________________________________________________

#chen='大蓝游戏'
chen=['abcd','chenwei']
try:
    if isinstance(chen,str):
        print('chen的类型是:str')
    else:
        raise Exception("chen变量类型错误")#默认为 Exception
except Exception as e:
    print(e)




###___________________________________________自定义异常raise________________________________________________________
try:
    a = input("输入一个数:")
    if(not a.isdigit()):
        raise ValueError("a 必须是数字")
except ValueError as e:
    print("引发异常:",repr(e))
    #重新报异常
    raise



try:
    a = input("输入一个数:")
    print(type(a))
    if(not a.isdigit()):#isdigit检测字符串是否只由数字组成
        raise RuntimeError('自定义异常,触发except RuntimeErro')#触发except 下的RuntimeErro
    if isinstance(a,str):
        print('44444444444')
        print(a+56)#这里a是字符串
        
except RuntimeError as e:
    print("这里引发异常:",repr(e))
except:
    print('当没有捕获到就走万能异常')

 两种异常处理的写法:

try:
    print('第一层try')
    try:
        print('第二层try')##当第二层try没有异常时,就不走第二层except
        print('正常执行'+'333')
        print('异常执行' + '333'+2226) #写成异常(就会触发第二层except)
    except:
        print('第二层except')
        print('异常时执行1111111111111'+333) #写成异常(就会触发第一层except)
except:
    print('第一层except')
else:
    print('没有异常时才执行')




try:
    print('第一层try')
    print('正常执行' + '333')
    print('异常执行'+'333'+22)#触发异常
except:
    try:
        print('第二层try')
        print('正常执行1111111111111' )
        #print('异常时执行1111111111111'+333) #触发第二层except
    except:
        print('第二层except')
    else:
        print('第二层try正常时,才执行该语句')
else:
    print('第一层try正常时,才执行该语句')

 

 

连接地址:

https://blog.csdn.net/weixin_43158056/article/details/92798114 .................字符串常用操作 ,,正则测试工具带生成python代码

https://www.jb51.net/article/47956.htm .......................................................字符串常用函数操作

 https://www.cnblogs.com/twelvezuo/p/11727634.html ................................字符串常用函数操作2

https://blog.csdn.net/crq_zcbk/article/details/81103595 .............................python异常处理,python标准异常类型

https://mp.weixin.qq.com/s/s1YXeV0tBjaoBp8Yjpngpg ..............................字符串100钟处理方法

posted on 2017-12-25 09:26  chen_2987  阅读(122)  评论(0编辑  收藏  举报

导航