• 字符串


    字符串

    Python中字符串是内建的序列,我们可以使用引号('或")来创建字符串。所有标准的序列操作(索引、分片、乘法、判断成员资格、求长度、取最小值和最大值)对字符串同样适用。但是请注意字符串是不可变的!

    字符串和操作符

    • 字符串的创建和赋值

    In [1]: str1 = 'Hello world!'
    
    In [4]: str1
    Out[4]: 'Hello world!'
    
    In [3]: print(str1)
    Hello world!
    

    Python中字符串是不区分'和"的,这个和别的脚本语言有一定区别。

    • 访问字符串的值

    In [15]: str1
    Out[15]: 'Hello world!'
    
    In [16]: str1[-1]
    Out[16]: '!'
    
    In [17]: str1[2:4]
    Out[17]: 'll'
    
    In [18]: str1[2:5]
    Out[18]: 'llo'
    
    In [19]: str1[7:]
    Out[19]: 'orld!'
    
    In [20]: str1[:3]
    Out[20]: 'Hel'
    
    • 字符串的改变

    我们可以通过给一个变量赋值或者重赋值的方式“更新”一个已有的字符串。新的值可能与原有的值差不多,也有可能跟原有串完全不同。

    In [21]: str1
    Out[21]: 'Hello world!'
    
    In [22]: str1 = str1[:6] + 'Python'
    
    In [23]: str1
    Out[23]: 'Hello Python'
    
    In [24]: str1 = 'Hello world!'
    
    In [25]: str1
    Out[25]: 'Hello world!'
    

    和数字类型一样,字符串类型也是不可变的,所以你要改变一个字符串就必须通过创建一个新串的方式来实现。也就是说你不能只改变一个字符串中的一个字符或者一个子串,然而通过拼凑一个旧串的各个部分来得到一个新串是被允许的。

    • 删除字符和字符串

    注意:字符串是不可变的,所以你不能仅仅删除一个字符串里的某个字符,你能做的是清空一个空字符串,或者是把剔除了不需要的部分后的字符串组合起来形成一个新的字符串。

    In [41]: str1
    Out[41]: 'Hello Python'
    
    In [42]: str1 = str1[:3] + str1[4:]
    
    In [43]: str1
    Out[43]: 'Helo Python'
    

    清空和删除一个字符串:

    In [44]: str1 = ''
    
    In [45]: str1
    Out[45]: ''
    
    In [46]: del str1
    
    In [47]: str1
    

    在大部分的应用程序里,没有必要显示的删除字符串。定义这个字符串的代码最终会结束,那时Python会自动释放这些字符串。

    • 切片

    Python中切片使用很灵活,常用在列表和字符串中。在切片的三个数字中一个月是起始的下标(包含此下标的值),第二个是最终下标(不包含此下标的值),最后一个是步进。三个数字都可以省略,下标就看其如何使用。

    In [53]: str2 = '0123456789'
    
    In [54]: str2
    Out[54]: '0123456789'
    
    In [55]: str2[2:5]
    Out[55]: '234'
    
    In [56]: str2[2:]
    Out[56]: '23456789'
    
    In [57]: str2[:5]
    Out[57]: '01234'
    
    In [58]: str2[::2]
    Out[58]: '02468'
    
    In [59]: str2[-1:]
    Out[59]: '9'
    
    In [60]: str2[:-5]
    Out[60]: '01234'
    
    In [61]: str2[-2:-5]
    Out[61]: ''
    
    In [62]: str2[-7:-5]
    Out[62]: '34'
    

    正是由于切片的灵活所以这个还是多做练习,请找出其中的规律。代码是需要练习写出来的光看书和视频不练习还是等于没有学。

    • 成员操作符

    成员操作符用于判断一个字符或者一个子串中的字符是否出现在另一个字符串中。出现则返回True。否则返回False。注意,成员操作符不是用来判断一个字符串是否包含另一个字符串的,这样的功能可以使用find()或者index()方法完成。

    In [63]: 'bc' in 'abcd'
    Out[63]: True
    
    In [64]: 'bc' in 'abd'
    Out[64]: False
    
    In [65]: 'bd' in 'abcd'
    Out[65]: False
    
    • 连接符

    我们可以通过连接操作符来从原有字符串获得一个新的字符串,下面举例。

    In [1]: Str = 'Defence ' + 'of ' + 'the ' + 'Ancients.'
    
    In [2]: Str
    Out[2]: 'Defence of the Ancients.'
    
    • 封包和解包

    In [1]: str1='0123456789'
    
    In [2]: a,_,b,*_,c=str1
    
    In [3]: a
    Out[3]: '0'
    
    In [4]: b
    Out[4]: '2'
    
    In [5]: c
    Out[5]: '9'
    

    字符串的方法

    • join

    格式

    string.join(seq)
    

    以string作为分隔符,将seq中所有的元素(字符串表示)合并成为一个新的字符串。

    In [6]: str2=['Defence','of','the','Ancients']
    
    In [7]: ' '.join(str2)
    Out[7]: 'Defence of the Ancients'
    
    • split

    格式

    string.spilt(str='',num=string.count(str))
    

    以str为分隔符切片string,如果num有指定值,则仅分隔num个字符串。分隔从左边开始。

    In [32]: str2
    Out[32]: 'Defence of the Ancients is DOTA!'
    
    In [33]: str2.split()
    Out[33]: ['Defence', 'of', 'the', 'Ancients', 'is', 'DOTA!']
    
    
    In [35]: str2.split('is',1)
    Out[35]: ['Defence of the Ancients ', ' DOTA!']
    
    In [36]: str2.split('is',2)
    Out[36]: ['Defence of the Ancients ', ' DOTA!']
    
    In [46]: str2.split(' ',-1)
    Out[46]: ['Defence', 'of', 'the', 'Ancients', 'is', 'DOTA!']
    
    In [47]: str2.split(' ',1)
    Out[47]: ['Defence', 'of the Ancients is DOTA!']
    
    In [48]: str2.split(' ',2)
    Out[48]: ['Defence', 'of', 'the Ancients is DOTA!']
    
    In [49]: str2.split(' ',-2)
    Out[49]: ['Defence', 'of', 'the', 'Ancients', 'is', 'DOTA!']
    
    • rsplit

    格式

    string.rspilt(str='',num=string.count(str))
    

    以str为分隔符切片string,如果num有指定值,则仅分隔num个字符串。分隔从右边开始。

    In [54]: str2.rsplit(' ',1)
    Out[54]: ['Defence of the Ancients is', 'DOTA!']
    
    In [55]: str2.split(' ',1)
    Out[55]: ['Defence', 'of the Ancients is DOTA!']
    
    • splitlines

    格式

    splitlines(num=string.count('
    ')
    

    按照行分隔,返回一个包含各行作为元素的列表,如果num指定则仅切片num行。

    In [58]: str3
    Out[58]: 'Defence of the
    Ancients is
    DOTA!'
    
    In [59]: str3.splitlines()
    Out[59]: ['Defence of the', 'Ancients is', 'DOTA!']
    
    In [61]: str3.splitlines(True)
    Out[61]: ['Defence of the
    ', 'Ancients is
    ', 'DOTA!']
    
    In [62]: str3.splitlines(1)
    Out[62]: ['Defence of the
    ', 'Ancients is
    ', 'DOTA!']
    
    In [63]: str3.splitlines(2)
    Out[63]: ['Defence of the
    ', 'Ancients is
    ', 'DOTA!']
    
    In [65]: str3.splitlines(-1)
    Out[65]: ['Defence of the
    ', 'Ancients is
    ', 'DOTA!']
    
    • partition

    格式

    string.partition(str)
    

    有点像find()和split()的结合体,从str出现的第一个位置起,把字符串string分成一个3元组(string_pre_str,str,string_post_str),如果string中不包含str则string_pre_str==string。

    In [75]: str2
    Out[75]: 'Defence of the Ancients is DOTA!'
    
    In [78]: str2.partition(' ')
    Out[78]: ('Defence', ' ', 'of the Ancients is DOTA!')
    
    In [79]: str2
    Out[79]: 'Defence of the Ancients is DOTA!'
    
    In [80]: str2.partition(' ')
    Out[80]: ('Defence', ' ', 'of the Ancients is DOTA!')
    
    In [81]: D,_,OTA=str2.partition(' ')
    
    In [82]: D
    Out[82]: 'Defence'
    
    In [83]: OTA
    Out[83]: 'of the Ancients is DOTA!'
    
    • capitalize

    格式

    string.capitatize()
    

    把字符串的第一个字符大写。

    In [88]: str2
    Out[88]: 'Defence of the Ancients is DOTA!'
    
    In [89]: str2.capitalize()
    Out[89]: 'Defence of the ancients is dota!'
    
    • title

    格式

    string.title()
    

    返回“标题化”的string,就是说所有单词都是以大写开始,其余字母均为小写。

    In [90]: str2.title()
    Out[90]: 'Defence Of The Ancients Is Dota!'
    
    • istitle

    格式

    string.istitle()
    

    如果string是标题化的则返回True,否则返回False。

    In [91]: str2.istitle()
    Out[91]: False
    
    In [92]: str4=str2.title()
    
    In [93]: str4.istitle()
    Out[93]: True
    
    • lower

    格式

    string.lower()
    

    转换string中所有大写字符为小写。

    In [95]: str2
    Out[95]: 'Defence of the Ancients is DOTA!'
    
    In [96]: str2.lower()
    Out[96]: 'defence of the ancients is dota!'
    
    • islower

    格式

    string.islower()
    

    如果string中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回True,否则返回False。

    In [97]: str2.islower()
    Out[97]: False
    
    • upper

    格式

    string.upper()
    

    转换string中的小写字母为大写。

    In [105]: str2
    Out[105]: 'Defence of the Ancients is DOTA!'
    
    In [106]: str2.upper()
    Out[106]: 'DEFENCE OF THE ANCIENTS IS DOTA!'
    
    • isupper

    格式

    string.isupper()
    

    如果string中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回True,否则返回False。

    In [107]: str2.isupper()
    Out[107]: False
    

    扩展
    大小写转化通常用在做比较得时候,当我们需要忽略大小写比较时, 通常统一转化为全部大写或者全部小写再做比较。

    In [108]: str2.lower().upper()
    Out[108]: 'DEFENCE OF THE ANCIENTS IS DOTA!'
    
    In [109]: str2.upper().lower()
    Out[109]: 'defence of the ancients is dota!'
    
    • swapcase

    格式

    string.swapcase()
    

    翻转string中的大小写字母。

    In [110]: str2.swapcase()
    Out[110]: 'dEFENCE OF THE aNCIENTS IS dota!'
    
    • center

    格式

    string.center(width)
    

    返回一个原字符串居中,并使用空格填充至长度width的新字符串。

    In [111]: str2.center(88)
    Out[111]: '                            Defence of the Ancients is DOTA!                            '
    
    In [113]: str2.center(88,'#')
    Out[113]: '############################Defence of the Ancients is DOTA!############################'
    
    • ljust

    格式

    string.ljust(width)
    

    返回一个原字符串左对齐,并使用空格填充至长度width的新字符串。可以指定填充符号,指定的填充符号必须是单个字符或数字。

    In [117]: str2.ljust(88)
    Out[117]: 'Defence of the Ancients is DOTA!                                                        '
    
    In [119]: str2.ljust(88,'$')
    Out[119]: 'Defence of the Ancients is DOTA!$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$'
    
    • rjust

    格式

    string.rjust(width)
    

    返回一个原字符串右对齐,默认使用空格填充至长度width的新字符串。可以指定填充符号,指定的填充符号必须是单个字符或数字。

    In [124]: str2.rjust(88)
    Out[124]: '                                                        Defence of the Ancients is DOTA!'
    
    In [125]: str2.rjust(88,'&')
    Out[125]: '&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&Defence of the Ancients is DOTA!'
    
    • zfill

    格式

    string.zfill(width)
    

    返回长度为width的字符串,原字符串string右对齐,前面填充0.

    In [126]: str2.zfill(88)
    Out[126]: '00000000000000000000000000000000000000000000000000000000Defence of the Ancients is DOTA!'
    
    • strip

    格式

    string.strip([chars])
    

    出去string字符串中最左边和最右边chars字符,不写chars则清楚空格、 、 、 、v or x0b、f or x0c、x1c、x1d、x1e、x85、u2028、u2029,若填写字符则清楚指定的字符,填写字符可以为多个。

    In [28]: str1='f  x1e    ####  DOTA   ## ****  
       	  
       x1c    '
    
    In [29]: str1.strip()
    Out[29]: '####  DOTA   ## ****'
    
    In [21]: str1='####  DOTA   
       	  ###****'
    
    In [22]: str1.strip('*#')
    Out[22]: '  DOTA   
       	  '
    
    In [31]: str1.strip('*#D')
    Out[31]: '  DOTA   
       	  '
    
    In [32]: str1.strip('*# ')
    Out[32]: 'DOTA   
       	'
    
    • lstrip

    格式

    string.lstrip([chars])
    

    去除string中左边指定的字符,和strip格式一样,但是只是去除左边的。

    In [34]: str1='f    ####  DOTA   
       	  ###****'
    
    In [35]: str1.lstrip()
    Out[35]: '####  DOTA   
       	  ###****'
    
    In [36]: str1='####  DOTA   
       	  ###****'
    
    In [37]: str1.lstrip(' #')
    Out[37]: 'DOTA   
       	  ###****'
    
    • rstrip

    格式

    string.rstrip([chars])
    

    去除string中右边指定的字符,和strip格式一样,但是只是去除右边的。

    In [40]: str1
    Out[40]: '####  DOTA   
       	  ###****'
    
    In [41]: str1.rstrip('* #')
    Out[41]: '####  DOTA   
       	'
    
    • startswith

    格式

    startswith(obj,beg=0,end=len(string)) 
    

    检查字符串是否是以obj开头,是则返回True,否则返回False。如果beg和end指定值,则在指定范围内检查。

    In [42]: str1
    Out[42]: '####  DOTA   
       	  ###****'
    
    In [43]: str1.startswith('#')
    Out[43]: True
    
    In [44]: str1.startswith('####')
    Out[44]: True
    
    In [45]: str1.startswith('#####')
    Out[45]: False
    
    In [52]: str1.startswith('DOTA',6)
    Out[52]: True
    
    • endswith

    格式

    endswith(obj,beg=0,end=len(string)) 
    

    检查字符串是否是以obj结束,是则返回True,否则返回False。如果beg和end指定值,则在指定范围内检查。

    In [59]: str1
    Out[59]: '####  DOTA   
       	  ###****'
    
    In [67]: len(str1)
    Out[67]: 27
    
    In [74]: str1.endswith('***',22)
    Out[74]: True
    
    In [75]: str1.endswith('***',21)
    Out[75]: True
    
    In [80]: str1.endswith('###',1,24)
    Out[80]: False
    
    In [81]: str1.endswith('###',1,23)
    Out[81]: True
    
    • isdigit()

    语法

    string.isdigit()
    

    如果string只包含数字则返回True,否则返回False。

    In [85]: str2
    Out[85]: '012345678'
    
    In [86]: str2.isdigit()
    Out[86]: True
    
    In [87]: str3='012345abc'
    
    In [88]: str3.isdigit()
    Out[88]: False
    
    • isalnum

    语法

    string.isalnum()
    

    如果string中至少有一个字符并且所有字符都是字母或数字则返回True,否则返回Fales。

    In [91]: str3
    Out[91]: '012345abc'
    
    In [92]: str3.isalnum()
    Out[92]: True
    
    In [93]: str1
    Out[93]: '####  DOTA   
       	  ###****'
    
    In [94]: str1.isalnum()
    Out[94]: False
    
    • isalpha

    格式

    string.isalpha()
    

    如果string中至少有一个字符并且所有字符都是字母则返回True,否则返回False。

    In [97]: str3
    Out[97]: '012345abc'
    
    In [98]: str3.isalpha()
    Out[98]: False
    
    In [99]: str4='DOTA'
    
    In [100]: str4.isalpha()
    Out[100]: True
    
    • isdecimal

    格式

    string.isdecimal()
    

    如果string只包含十进制数字则返回True,否则返回False。

    In [101]: str2
    Out[101]: '012345678'
    
    In [102]: str2.isdecimal()
    Out[102]: True
    
    In [103]: str3
    Out[103]: '012345abc'
    
    In [104]: str3.isdecimal()
    Out[104]: False
    
    • count

    格式

    string.count(str,beg=0,end=len(string))
    

    返回str在string里面出现的次数,如果beg或者end指定则在指定的范围查找str出现的次数。

    In [110]: str4='*****   DOTA  dota #####'
    
    In [111]: str4.count('*')
    Out[111]: 5
    
    In [112]: str4.count('**')
    Out[112]: 2
    
    In [113]: str4.count('**',3)
    Out[113]: 1
    
    In [114]: str4.count('**',2)
    Out[114]: 1
    
    • find

    格式

    string.fing(str,beg=0,end=len(string))
    

    检测str是否包含在string中,如果beg和end指定了范围,则检测是否包含在指定范围内,如果是返回开始的索引值,否则返回-1.

    In [115]: str4
    Out[115]: '*****   DOTA  dota #####'
    
    In [116]: str4.find('dota')
    Out[116]: 14
    
    In [4]: str4.find('dotaer')
    Out[4]: -1
    
    In [117]: str4.lower().find('dota')
    Out[117]: 8
    
    • rfind

    格式

    string.rfind(str,beg=0,end=len(strint))
    

    类是find()方法,不过是从右开始查找。

    In [118]: str4
    Out[118]: '*****   DOTA  dota #####'
    
    In [119]: str4.rfind('DOTA')
    Out[119]: 8
    
    In [120]: str4.upper().rfind('DOTA')
    Out[120]: 14
    
    In [6]: str4.rfind('DOTAER')
    Out[6]: -1
    
    • index

    格式

    string.index(str,beg=0,end=len(string))
    

    和find方法差不多,只不过如果str不在string中报一个ValueError异常。

    In [9]: str4
    Out[9]: '*****   DOTA  dota #####'
    
    In [10]: str4.index('dota')
    Out[10]: 14
    
    • rindex

    格式

    string.rindex(str,beg=0,end=len(string))
    

    类似于index()方法,不过是从右边开始查找。

    • replace

    格式

    string.replace(str1,str2,num)
    

    把string中的str1替换成str2,如果num指定则替换不超过num次。

    In [14]: str4
    Out[14]: '*****   DOTA  dota #####'
    
    In [21]: str4.replace('#','*',1)
    Out[21]: '*****   DOTA  dota *####'
    
    In [22]: str4.replace('#','*',2)
    Out[22]: '*****   DOTA  dota **###'
    
  • 相关阅读:
    python项目打包成exe
    sql同比环比计算
    七款好看文字样式纯css
    一站式智能芯片定制技术
    实战清除电脑上恶意弹出广告窗口
    GAAFET与FinFET架构
    MIPI多媒体接口
    Intel GPU实现游戏与数据中心
    芯片倒爷赚钱术
    Cache Memory技术示例
  • 原文地址:https://www.cnblogs.com/cuchadanfan/p/5926067.html
Copyright © 2020-2023  润新知