Python学习-字符串操作

字符串的常用操作包括但不限于以下操作:

字符串的替换、删除、截取、复制、连接、比较、查找、分割等

 1 #!/usr/bin/env python3
 2 # -*- coding: utf-8 -*-
 3 # @Time    : 2018/5/2 16:41
 4 # @Author  : yang
 5 # @File    : str.py
 6 # @Software: PyCharm
 7 #字符串操作
 8 name = 'my \tname is {name},and i am {year} old'
 9 print(name.capitalize())    #capitalize:将字符串的首字母大写:My     name is {name},and i am {year} old
10 print(name.count('a'))     #5
11 print(name.center(50,'*'))      #将字符串居中,并在两端填充'*':******my     name is {name},and i am {year} old******
12 print(name.endswith('ex'))       #判断以什么结尾,若正确,则打印输出'True',否则'False'
13 print(name.expandtabs(tabsize=30))     #my                            name is {name},and i am {year} old
14 print(name.expandtabs(30))     #my                            name is {name},and i am {year} old
15 print(name.find('name'))     #查找'name'
16 print(name.format(name='alex',year=26))     #格式化输出:my name is alex,and i am 26 old
17 print(name.format_map({'name':'alex','year':26}))     #格式化输出
18 print(name.isalnum())    #False
19 #isalnum:包含所有的英文字符和0-9
20 print(name.isalpha())    #是否为纯英文字符
21 print('12'.isdecimal())      #是否为十进制
22 print('28'.isdigit())     #是否为整数
23 print('123'.isidentifier())     #判断是不是一个合法的标识符(变量名):False,变量名不能以数字开头
24 print('a123'.isidentifier())     #判断是不是一个合法的标识符(变量名):True,变量名以英文字母开头
25 print('a 123'.isidentifier())     #判断是不是一个合法的标识符(变量名):False,变量名中间不能有空格
26 print('我123'.isidentifier())     #判断是不是一个合法的标识符(变量名):True,变量名可以采用中文
27 print('a Bc'.islower())       #判断一个字符串是否全部为小写
28 print('1.23'.isnumeric())       #判断是否为数字(只有数字):False
29 print('333'.isnumeric())       #判断是否为数字(只有数字):True
30 print('my name is'.istitle())    #False
31 print('My Name Is'.istitle())    #True:判断字符串中各元素首字母是否都大写
32 print('My Name Is'.isprintable())   #True
33 #判断一个字符串是否为可以打印的,在字符串中没意义,字符串都是可以打印的,当为tty file时,
34 print('My Name Is'.isupper())   #False
35 print('MY NAME IS'.isupper())   #True
36 #join
37 print(''.join(['1','2','3']))    #str:123
38 print(''.join(('1','2','3')))     #str:123
39 print(','.join(['1','2','3']))    #1,2,3
40 print('+'.join(['1','2','3']))    #1+2+3
41 print(type(''.join(('1','2','3'))))
42 print(type(''.join(['1','2','3'])))
43 print(name.ljust(50,'*'))     #my     name is {name},and i am {year} old************
44 print(name.rjust(50,'*'))     #************my     name is {name},and i am {year} old
45 print('------')
46 print('\nalex\n'.lstrip())     #从左边去掉回车和空格
47 print('------')
48 print('\nalex\n'.rstrip())     #从右边去掉回车和空格
49 print('\nalex\n'.strip())     #去掉两边的回车和空格
50 print('----')
51 
52 p = str.maketrans('abcdefli','123456$@')    #maketrans:用于创建字符映射的转换表
53 print('alex li'.translate(p))    #1$5x $@
54 
55 print('alex li'.replace('l','L'))   #aLex li
56 print('alex li'.rfind('l'))   #从左往右数,最右边的那个对应字符的下标,'alex li'中'l'最有边的下标为5
57 print('alex li yang'.split())     #['alex', 'li', 'yang'],默认分隔符为空格
58 print('alex li'.split('l'))     #['a', 'ex ', 'i'],此时'l'被当做了分隔符
59 print('1+2+3+4'.split('+'))   #['1', '2', '3', '4']
60 print('1+2\n+3+4'.splitlines())   #分隔符为换行符:['1+2', '+3+4']
61 print('Alex Li'.swapcase())   #aLEX lI,将字符串中的大写变为小写,小写变为大写
62 print('alex li'.zfill(50))    #指定宽度,不够的用'0'填充:0000000000000000000000000000000000000000000alex li
1 #capitalize:字符串首字母大写:capitalize-将字符串的首字母大写,其他字母小写
2 name = 'swhthaitun'
3 name.capitalize()
4 print(name.capitalize())
1 #casefold:字符串所有字母小写:casefold-将字符串中所有的大写字符转换成小写字符
2 name = 'HelloWorld'
3 name.casefold()    #将所有语言的字符转换为小写
4 name.lower()     #lower只对ASCII有效,对其他语言无效
5 print(name.casefold())
6 print(name.lower())
1 #center:字符串宽度填充,使用原有字符串+填充字符构成指定长度的新的字符串
2 name = 'swhthaitun'
3 #在原有字符串两端填充相同数目的字符
4 print(name.center(15))
5 print(name.center(16,'*'))
6 name2 = 'HelloWorld'
7 print(name.center(20,'*'))
1 #count:统计某个字符在字符串中出现的次数,或者是在字符串的指定区间内完成上述操作
2 name = 'swhthaitun'
3 result = name.count('h')    
4 print(result)     #2
5 result2 = name.count('h',0,3)
6 print(result2)    #1
7 name2 = 'HelloWorld'
8 result3 = name2.count('W')    #不能换成'w',Python对大小写敏感
9 print(result3)    #1
1 #encode:对字符串进行编码操作
2 name = 'swhthaitun'
3 name.encode()
4 print(name.encode())    #b'swhthaitun'
1 #endwith:判断字符串是否以某个字符或字符串结尾,返回值为布尔值
2 name = 'swhthaitun'
3 result1 = name.endswith('s')
4 print(result1)   #False
5 result2 = name.endswith('n')
6 print(result2)   #True
7 result3 = name.endswith('tun')
8 print(result3)   #True
1 #expandtabs:将制表符'\t'转换成制定宽度的tab键分割,默认的tabsize=8
2 li = 'sw\tht'
3 li.expandtabs(4)
4 print(li.expandtabs(4))     #sw  ht
5 print(li.expandtabs())     #sw      ht
1 #find:在字符串中查找指定字符串,找不到事返回-1
2 name = 'swht'
3 name.find('s')
4 name.find('h')
5 name.find('a')
6 print(name.find('s'),name.find('h'),name.find('a'))   #0 2 -1
1 #format:格式化输出字符串
2 li = "I'm {},{}"    #其中{}为占位符
3 result = li.format('swht','欢迎来中国')
4 print(result)    #I'm swht,欢迎来中国
1 #__contains__:判断字符串中是否包含某段字符,返回值为布尔值
2 name = 'swhtkkskjj'
3 result = name.__contains__('swht')
4 print(result)    #True
1 #index:在字符串中查找指定的字符串,找不到时直接报错
2 name = 'swhthaitun'
3 result1 = name.index('h')
4 #result2 = name.index('m')
5 print(result1)    #2
6 #print(result2)     #字符串中没有'm',异常报错
1 #join:字符串拼接
2 name = 'swhthaitun'
3 '*'.join(name)
4 name.join('ab')
5 print(name.join('ab'))    #aswhthaitunb
6 print('*'.join(name))     #s*w*h*t*h*a*i*t*u*n
1 #isalnum:检查判断字符串是否包含字母或数字
2 name1 = 'swhthaitun'
3 name2 = '12345'
4 result1 = name1.isalnum()
5 result2 = name2.isalnum()
6 print(result1)    #True
7 print(result2)    #True
1 #isalpha:检测判断字符串是否完全由字母组成
2 name = 'swhthaitun'
3 result = name.isalpha()
4 print(result)    #True
1 #isdecimal:检查字符串是否只包含十进制字符
2 name = '123456'
3 result = name.isdecimal()
4 print(result)     #True
1 # isdecimal()
2 # True: Unicode数字,,全角数字(双字节)
3 # False: 罗马数字,汉字数字
4 # Error: byte数字(单字节)
1 #isdigit:检测字符串是否只有数字组成
2 name = '12345'
3 result = name.isdigit()
4 print(result)    #True
1 # isdigit()
2 # True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
3 # False: 汉字数字
4 # Error: 无
1 #isidentifier:检测字符串是否以字母开头
2 name = 'swhthaitun'
3 result = name.isidentifier()
4 print(result)   #True
5 
6 name2 = '2swhthaitun'
7 result2 = name2.isidentifier()
8 print(result2)     #False 
1 #isnumeric:检测字符串是否只有数字组成,这种方法只针对于unicode对象
2 name = 'swhthaitun'
3 result = name.isnumeric()
4 print(result)     #False
5 
6 name2 = '123545'
7 result2 = name2.isnumeric()
8 print(result2)    #True  
1 #isprintable:判断字符串中所有字符是否都属于可见字符
2 name = '\tPuppy'
3 result = name.isprintable()
4 print(result)      #False
5 
6 name2 = 'swhthaitun'
7 result2 = name2.isprintable()
8 print(result2)      #True   
 1 #isspace:检测字符串是否全部为空格
 2 #istitle:检测字符串中每一个连续的字符串的的首字母是否大写
 3 #name = 'Puppy'    #True
 4 #name = 'Puppy Abc'    #True
 5 #name = '   Puppy'    #True
 6 # name = 'a Puppy'    #False
 7 # print(name.istitle())
 8 
 9 #isupper:判断字符串中所有的字母是否都是大写字母
10 #lower:将所有字母转换为小写字母
11 #lstrip:去除字符串左边开头的空格
12 #rstrip:去除字符串右边结尾的空格
13 #strip:去除字符串两边的空格
1 #maketrans:用于创建字符映射的转换表,对于接收两个参数的调用方式,第一个参数是字符串,表示需要转换的字符
2 #第二个参数表示字符串需要转换的目标(没怎么看懂)
3 intab = 'swhtr'
4 outtab = '12345'
5 name = 'swhtr hjjksknsnjmk'
6 print(name.maketrans(intab,outtab))   #{115: 49, 119: 50, 104: 51, 116: 52, 114: 53}
1 #partition:根据指定的分隔符对字符串进行分割
2 name = 'ls'
3 li = 'hhsslswhtolljm'
4 result = li.partition(name)
5 print(result)     #('hhss', 'ls', 'whtolljm')
 1 #replace:将字符串中的old(旧字符串)替换成new(新字符串),如果指定第三个参数max,则替换不超过max次
 2 '''语法:str.replace(old, new[, max])
 3 参数:old -- 将被替换的子字符串。
 4       new -- 新字符串,用于替换old子字符串。
 5       max -- 可选字符串, 替换不超过 max 次'''
 6 str = 'this is string example.....wow!!! this is really string'
 7 str_new = str.replace('is','was')
 8 str_new2 = str.replace('is','was',3)
 9 print(str_new)    #thwas was string example.....wow!!! thwas was really string
10 print(str_new2)   #thwas was string example.....wow!!! thwas is really string  
1 #split:字符串分割,默认是空格,
2 #语法:str.split(str="", num=string.count(str)).
3 #str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。num--分割次数
4 name = 'swhthaitun'
5 result = name.split('h')
6 result2 = name.split('h',1)
7 print(result)   #['sw', 't', 'aitun']
8 print(result2)  #['sw', 'thaitun']
1 #__add__:在字符串后面增加指定的字符或者字符串
2 name = 'swht'
3 result = name.__add__('e')
4 print(result)     #swhte
5 li = 'hjh'
6 result2 = name.__add__(li)
7 print(result2)     #swhthjh
1 #__eq__:判断字符串是否相等,返回值为布尔
2 name = 'swht'
3 li = 'test'
4 result = name.__eq__(li)
5 print(result)    #False
posted @ 2018-03-26 20:35  偶尔写点代码  阅读(335)  评论(0编辑  收藏  举报