zoukankan      html  css  js  c++  java
  • Python——数据类型之str

    本篇主要内容:

    1、str元素的访问

    2、str内置43个方法使用示例

    str就是储存各种东西的字符串。

    他的方法也是最多的。。。有各种各样的神奇魔法。

    1、str的访问,str可以想列表那样访问每一个元素。

    a='i love albert'
    print(a)
    for i in a:
        print(i)
    print(a[-6:])

    输出

    i
     
    l
    o
    v
    e
     
    a
    l
    b
    e
    r
    t
    albert

    这就不多复习了。

    2、str类型中自带的方法

    (1) capitalize(self):让第一个字母大写,其他全部为小写。。。觉得好像并没什么用。。。。

    a='i love Albert'
    print(a.capitalize())

    输出

    I love albert

    (2)casefold(self):直观的来说,他就是把所有字母都变为小写。官方文档里写的

    Return a version of S suitable for caseless comparisons.

    但会一个不分大小写的S(字符串)版本

    a='I LOVE Albert'
    print(a.casefold())

    输出

    i love albert

    (3)center(self, width, fillchar=None):返回一个把字符串放在中间的长度为width的字符串,两边用fillchar填充,默认为空格

         注意:width要大于原字符串的长度,否则会返回原字符串。

    a='I Love Albert'
    print(a.center(20,'A'))

    输出

    AAAI Love AlbertAAAA

    (4)count(self, sub, start=None, end=None):在start~end之间寻找字符串sub出现的次数。默认查找整个字符串

    a='I Love Love Love Love Albert'
    print(a.count('Love'))

    输出

    4

    (5)encode(self, encoding='utf-8', errors='strict'):将字符串编码

    S.encode(encoding='utf-8', errors='strict') -> bytes

    Encode S using the codec registered for encoding. Default encoding
    is 'utf-8'. errors may be given to set a different error
    handling scheme. Default is 'strict' meaning that encoding errors raise
    a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
    'xmlcharrefreplace' as well as any other name registered with
    codecs.register_error that can handle UnicodeEncodeErrors.

    encoding是设置编码规则:比较常用的就是‘utf-8’,‘utf-16’,‘gbk’,‘gb2312’

    error是设置编码错误时的处理(我就遇到过这个问题,比如一些小表情,根本没办法编码,会报错)

    会返回一个bytes类型

    a='I Love Albert'
    print(a.encode())
    print(a.encode('gbk','ignore'))

    输出

    b'I Love Albert'
    b'I Love Albert'

    这好像看不出来差别,那就对了,因为。。。他们的区别是中文。。。

    a='I Love Albert 我爱你中国'
    print(a.encode())
    print(a.encode('gbk','ignore'))

    输出

    b'I Love Albert xe6x88x91xe7x88xb1xe4xbdxa0xe4xb8xadxe5x9bxbd'
    b'I Love Albert xcexd2xb0xaexc4xe3xd6xd0xb9xfa'

    后面的就是对汉字的二进制编码

    有编码就会有解码

    bytes有个方法。就是decode()用来解码的

    a='I Love Albert 我爱你中国'
    b=a.encode()#编码为utf-8
    print(b)
    c=a.encode('gbk','ignore')#编码为gbk
    print(c)
    print(c.decode('utf-8',errors='ignore'))#用utf-8解码gbk
    print(c.decode('gbk'))#用gbk解码gbk

    输出

    b'I Love Albert xe6x88x91xe7x88xb1xe4xbdxa0xe4xb8xadxe5x9bxbd'
    b'I Love Albert xcexd2xb0xaexc4xe3xd6xd0xb9xfa'
    I Love Albert Ұй
    I Love Albert 我爱你中国

    可以看到用utf-8解码gbk就会。。。乱码。他们是不同的规则。加上‘ignore’他也会转码。但不加,会报错。

    Traceback (most recent call last):
    File "C:/Users/admin/PycharmProjects/temp.py", line 6, in <module>
    print(c.decode('utf-8',))#用utf-8解码gbk
    UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 14: invalid continuation byte

    (6)endswith(self, suffix, start=None, end=None):判断字符串是不是以suffix结尾。返回True或者false

    a='I Love Albert 我爱你中国'
    print(a.endswith('中国'))

    输出

    True

    (7)expandtabs(self, tabsize=8)

    S.expandtabs(tabsize=8) -> str

    Return a copy of S where all tab characters are expanded using spaces.
    If tabsize is not given, a tab size of 8 characters is assumed.

    把字符串里的tab键换成空格。。。tab好像就是代表四个空格。好像没什么用呀。。。emm...存在即有理,是我太菜。

    (8)find(self, sub, start=None, end=None):在start~ends区间内找到第一个sub的index。

    a='I Love Love Love Albert'
    print(a.find('Love'))

    输出

    2

    (9)format(self, *args, **kwargs):用来格式化内容。觉得这个挺好用的

    a='I Love {} {} Albert'
    print(a.format('love','LOVE'))#分别填入到两个{}中

    a='I Love {1} {0} {1} Albert' print(a.format('love','LOVE'))#{}中的数字代表formart中输入两个字符串的索引。 b='姓名:{0[0]} 学号{0[1]}' cs=[['Y','1'],['Z','2'],['P','3']] for c in cs: print(b.format(c))

    输出

    I Love love LOVE Albert
    I Love LOVE love LOVE Albert
    姓名:Y    学号1
    姓名:Z    学号2
    姓名:P    学号3

    这个对于格式化输出就贼好用了,差不多相当于C里面printf的%了。

    (10)format_map(self, mapping):类似于format()不过可以更方便的使用。

    a={
        'name':'albert',
    'country':'henan'
    }
    print('{name} was born in {country}'.format_map(a)) 

    输出

    albert was born in henan

    看出来区别了吧,format里面是用index去区分不同的位置的。而这个可以可用一个字典。就很舒服。(字典下一节复习)

    (11)index(self, sub, start=None, end=None):找sub内容在字符串中的index索引值(在[start,end)之间)sub如果是多个字符,就返回第一个字符的index

    a='I Love Albert'
    print(a.index('Love'))

    输出

    2

    如果找不到会报:、

    Traceback (most recent call last):
    File "C:/Users/admin/PycharmProjects/temp.py", line 3, in <module>
    print(a.index('love'))
    ValueError: substring not found

    (12)isalnum(self):判断字符串里面是不是全部都是字母或者数字(注意数字与ASCII码的区别) 

    a='I Love Albert'
    print(a.isalnum())
    b='5201314'
    print(b.isalnum())

    输出

    False
    True

    因为a里面有空格,所以不是全为字母或数字。

    (13)isalpha(self):判断字符串里面是不是全为字母

    a='I Love Albert'
    print(a.isalpha())
    
    b='520Albert'
    print(b.isalpha())
    
    c='ILoveAlbert'
    print(c.isalpha())

    输出

    False
    False
    True

    (14) isdecimal(self):字符串里面是不是全为十进制数

    Return true if all characters in the string are decimal characters and there is at least one character, false otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

    这是官方文档里的解释

    翻译过来就是

    如果字符串中的所有字符都是十进制字符并且至少有一个字符,则返回true,否则返回false。十进制字符是那些可用于在基数10中形成数字的字符,例如,U + 0660,ARABIC-INDIC DIGIT ZERO。正则小数字符是Unicode常规类别“Nd”中的字符。

    这个感觉很不常用,我就不花时间研究了。

    示例一个

    a='I Love Albert'
    print(a.isdecimal())
    
    b='520'
    print(b.isdecimal())
    
    c='520Albert'
    print(c.isdecimal())

    输出

    False
    True
    False

    (15)isdigit(self)这个就是判断是不是全为数字啦。也能识别十进制数字格式

    a='I Love Albert'
    print(a.isdigit())
    
    b='520'
    print(b.isdigit())
    
    c='520.1314'
    print(c.isdigit())

    输出

    False
    True
    False

    事实证明,,,他不能识别小数

    (15)isidentifier(self):判断是不是标识符,比如def,class,and这些

    a='I Love Albert'
    print(a.isidentifier())
    
    b='def'
    print(b.isidentifier())

    输出

    False
    True

     (16)islower(self):判断字符串里面是不是全部都是小写字母

    a='I Love Albert'
    print(a.islower())
    
    b='i love 1$ albert'
    print(b.islower())

    输出

    False
    True

    事实证明,他是在判断里面有没有大写,(就算有字符数字,也返回true)

    (17)isnumeric(self):简单的理解他是用来判断字符是不是数字的 ,跟isdigit()差不多,但比他更强大,

    Return true if all characters in the string are numeric characters, and there is at least one character, false otherwise. Numeric characters include digit characters, and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.

    翻译

    如果字符串中的所有字符都是数字字符,则返回true,并且至少有一个字符,否则返回false。 Numeric characters包括digit characters,以及具有Unicode数值属性的所有字符,例如,U + 2155,VULGAR FRACTION ONE FIFTH。形式上,数字字符是具有属性值Numeric_Type = Digit,Numeric_Type = Decimal或Numeric_Type = Numeric的字符。

    (18)  isprintable(self):判断字符串是否可以打印

    如果字符串中的所有字符都是可打印的或字符串为空,则返回true,否则返回false。不可打印的字符是Unicode字符数据库中定义为“其他”或“分隔符”的字符,但ASCII空间(0x20)除外,它被认为是可打印的。(请注意,此上下文中的可打印字符是在字符串上调用repr()时不应转义的字符。它与写入sys.stdout或sys.stderr的字符串的处理无关。)

    这个。。。不知道怎么举例。。。想不到Unicode没有定义的字符。。。

    (19)isspace(self):判断字符串里是不是全为空格(有啥用???)

    a='I Love Albert'
    print(a.isspace())
    b='     '
    print(b.isspace())

    输出

    False
    False

    (20)istitle(self):判断是不是标题,即每个英文单词首字母大写

    a='I Love Albert 123'
    print(a.istitle())
    b='I love albert 123'
    print(b.istitle())

    输出

    True
    False

    (21)isupper(self):判断字母是不是都为大写

    a='I LOVE ALBERT $$123'
    print(a.isupper())
    b='I love albert 123'
    print(b.isupper())

    输出

    True
    False

    它还是忽略了其他字符

    (22)join(self, iterable)

      比如a.join(b)就是把b用a串联起来。(b是可迭代的字符串)

    a='-'
    b='I love Albert'
    
    c=['I','love','Albert']
    print(a.join(b))
    print(a.join(c))

    输出

    I- -l-o-v-e- -A-l-b-e-r-t
    I-love-Albert

    这个在格式化输出的时候感觉还是挺有用的。

    (23)ljust(self, width, fillchar=None):将字符串拓展成width长度,并左对齐,后面补fillchar(默认为空格)(width小于原字符串则返回原字符串)

    a='I love Albert'
    print(a.ljust(20))
    print(a.ljust(20,'a'))

    输出

    I love Albert       
    I love Albertaaaaaaa

     (24) lower(self):把所有大写字母变为小写

    a='I love Albert'
    print(a.lower())

    输出

    i love albert

    (25)lstrip(self, chars=None):把字符串前面的空格删了。

    a='     I love Albert'
    print(a.lstrip())

    输出

    I love Albert

    其中形参char默认是None,也就是默认删除空格。也可以自己指定。

    a='IIIII love Albert'
    print(a.lstrip('I'))

    输出

     love Albert

    (26)maketrans(self, *args, **kwargs):

    此静态方法返回可用于str.translate()的转换表。如果只有一个参数,则它必须是将Unicode序数(整数)或字符(长度为1的字符串)映射到Unicode序数,字符串(任意长度)或无的字典。然后将字符键转换为序数。如果有两个参数,则它们必须是长度相等的字符串,并且在结果字典中,x中的每个字符将映射到y中相同位置的字符。如果有第三个参数,则它必须是一个字符串,其结果中的字符将映射到None。

    简单的来说,这个方法就是用来建立一个映射表。这个映射表可以用于translate()方法

    intab = "abcde"
    outtab = "12345"#这两个字符串内字符一一对应,长度必须相等
    tran=str.maketrans(intab,outtab)#生成映射表
    print(tran)
    
    a='IIIII love Albert'
    print(a.translate(tran))

    输出

    {97: 49, 98: 50, 99: 51, 100: 52, 101: 53}
    IIIII lov5 Al25rt

    (27)partition(self, sep):将字符串从第一个seq处。一分为三,seq前面,seq,seq后面

    a='I love Albert'
    print(a.partition('love'))

    输出

    ('I ', 'love', ' Albert')

    (28)replace(self, old, new, count=None)将前count个old换为new。默认换全部

    a='I love Albert and love QQ'
    print(a.replace('love','don`t love'))
    
    print(a.replace('love','don`t love',1))

    输出

    I don`t love Albert and don`t love QQ
    I don`t love Albert and love QQ

    (29)rfind(self, sub, start=None, end=None):在[start,end)区间找sub的最高索引值,也就是最后一个

    a='I love Albert and love QQ'
    print(a.find('love'))
    
    print(a.rfind('love'))

    输出

    2
    18

    (30)rindex(self, sub, start=None, end=None):跟上一个一样。这个找不到报错,上一个找不到返回-1

    (31)rjust(self, width, fillchar=None):右对齐

    a='I love Albert'
    print(a.ljust(20,'a'))#左对齐
    print(a.rjust(20,'a'))#右对齐

    输出

    I love Albertaaaaaaa
    aaaaaaaI love Albert

    (32)rpartition(self, sep):找最后一个seq拆分成三部分。

    a='I love Albert and love QQ'
    print(a.partition('love'))
    print(a.rpartition('love'))

    输出

    ('I ', 'love', ' Albert and love QQ')
    ('I love Albert and ', 'love', ' QQ')

    (33)def rsplit(self, sep=None, maxsplit=-1)这个是从尾到头拆分maxsplit。默认是按照空格拆分。可以设置seq按照seq拆分

    a='I love Albert and love QQ'
    print(a.rsplit())
    print(a.rsplit(maxsplit=2))
    print(a.rsplit('love'))

    输出

    ['I', 'love', 'Albert', 'and', 'love', 'QQ']
    ['I love Albert and', 'love', 'QQ']
    ['I ', ' Albert and ', ' QQ']

    (34)rstrip(self, chars=None):把字符串尾的char删了。默认删空格。

    a='I love Albert and love QQ'
    print(a.rstrip('Q'))

    输出

    I love Albert and love 

    (35)split(self, sep=None, maxsplit=-1):将字符串拆分为maxsplit份。默认按照空格,能拆就拆。

    a='I love Albert and love QQ'
    print(a.split())
    print(a.split(maxsplit=2))
    print(a.split('love'))

    输出

    ['I', 'love', 'Albert', 'and', 'love', 'QQ']
    ['I', 'love', 'Albert and love QQ']
    ['I ', ' Albert and ', ' QQ']

    (36)splitlines(self, keepends=None)按照换行符拆分,keepends是拆分后需不需要带上换行符。

    a='I love
    Albert
    
    and love QQ'
    print(a.splitlines())
    print(a.splitlines(True))

    输出

    ['I love', 'Albert', '', 'and love QQ']
    ['I love
    ', 'Albert
    ', '
    ', 'and love QQ']

    (37)startswith(self, prefix, start=None, end=None):在[start,end]之间是否以prefix开头

    a='I love Albert'
    print(a.startswith('I'))
    print(a.startswith('You'))

    输出

    True
    False

    (38)strip(self, chars=None):去除字符串头的chars字符,默认为空格。

    a='I love Albert'
    print(a.strip('I'))
    print(a.strip('You'))

    输出

     love Albert
    I love Albert

    (39)swapcase(self): 把大写变为小写,小写变为大写。

    a='I love Albert'
    print(a.swapcase())

    输出

    i LOVE aLBERT

     (40)title(self):将所有单词的第一个字母大写。

    a='I love Albert'
    print(a.title())

    输出

    I Love Albert

    (41)translate(self, table):上面的maketrans说过了。

    (42)upper(self):变为大写

    a='I love Albert'
    print(a.upper())

    输出

    I LOVE ALBERT

    (43)zfill(self, width):在左边插0扩充为width长

    a='I love Albert'
    print(a.zfill(20))

    输出

    0000000I love Albert
  • 相关阅读:
    spring mvc EL ModelAndView的 Model 值 在jsp中不显示
    maven修改本地仓库,远程仓库与中央仓库
    Maven 手动添加 JAR 包到本地仓库
    Maven项目的结构分析
    Maven 构建配置文件
    SVN使用出现的问题及解决方案
    Eclipse中SVN的安装步骤(两种)和使用方法
    Eclipse SVN 使用教程
    svn使用教程总结
    eclipse下配置安装ssm图文教程(web版)
  • 原文地址:https://www.cnblogs.com/albert-yzp/p/10081547.html
Copyright © 2011-2022 走看看