python(字符串魔法)【三】

妖精的绣舞 提交于 2020-04-08 04:51:53
num='00011'v=int(num,base=16)print(v)age=5v1=age.bit_length()print(v1)以0填充【右边】test='alex'v2=test.zfill(20)print(v2)test='alexalex'v3=test.count('ae')print(v3)断句(20字位符)test = "username\temail\tpassword\nlaiying\tying@q.com\t123\nlaiying\tying@q.com\t123\nlaiying\tying@q.com\t123"v = test.expandtabs(20)print(v)从开始往后找,找到第一个之后,获取其位置(find)test='alexalex'v4=test.find('al')print(v4)输出:0
test='alexalex'v4=test.find('al',2,3) #或者从第几个开始或者指定一个区间print(v4)# 输出:-1表示再此区间内不存在
判断字符串中是否只含有数字和字母,单纯数字或者字母也可test='123'v5=test.isalnum()print(v5)test='asd火狐'v5=test.isalpha()print(v5)test ='二'  # 2, ②v1 = test.isdecimal()v2 = test.isdigit()v3 = test.isnumeric()print(v1,v2,v3)是否存在不可显示的字符\t   制表符\n   换行test = "oiu2sd\tfkj"v = test.isprintable()print(v)输出false判断是否全部是空格test=' e'v4=test.isspace()print(v4)输出False,全为空格时输出true判断是否是标题(根据首字母大写判断)test= 'Some of the magic of strings is troublesome'v5=test.istitle()print(v5)v6=test.title()print(v6)v7=v6.istitle()print(v7)test = "Return True if all cased characters in S are uppercase and there is"v1 = test.istitle()print(v1)v2 = test.title()print(v2)v3 = v2.istitle()print(v3)输出:False        True将字符串中每个字符用指定的分隔符拼接起来test='如果S中的所有大小写字符都是大写字母,则返回True't='-'v=t.join(test)print(v)输出:如-果-S-中-的-所-有-大-小-写-字-符-都-是-大-写-字-母-,-则-返-回-T-r-u-e判断是否全部为小(大)写,转化为小(大)写test = "Alex"v1 = test.islower()v2 = test.lower()print(v1, v2)v1 = test.isupper()v2 = test.upper()print(v1,v2)移除指定字符串有限最多匹配(先匹配多的字符块体)test =‘9lexxexa'
v = test.lstrip('xa')
v = test.rstrip('xa')v = test.strip('xa')print(v)test.lstrip()test.rstrip()test.strip()去除左右空白v = test.lstrip()v = test.rstrip()v = test.strip()print(v)print(test)去除\t \nv = test.lstrip()v = test.rstrip()v = test.strip()print(v)对应关系替换test1='12345'test2='上山打老虎'v='1456389741136363587412596'm=str.maketrans('12345','上山打老虎')new_a=v.translate(m)print(new_a)以XX元素将字符串分割为三部分含s分界点test = "testasdsddfg"v = test.partition('s')print(v)v = test.rpartition('s')  #从右边开始以s为节点分割字符串print(v)
分割为指定个数
test="testasdsddfg"v=test.split('s',2)   #以s为节点全部分开不含s分界点print(v)
输出:['te', 'ta', 'dsddfg']
v = test.split('s')print(v)输出:['te', 'ta', 'd', 'ddfg'], 不加参数将以s为节点全部分割开
大小写转换test = "aLex"v = test.swapcase()print(v)输出:AlEX
将指定字符串替换为指定字符串
test = "alexalexalex"v = test.replace("ex",'bbb')    #替换print(v)v = test.replace("ex",'bbb',2)  #参数指定替换几个字符串print(v)# 输出:albbbalbbbalbbb#       albbbalbbbalex
 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!