美文网首页
py05_字符串内置方法

py05_字符串内置方法

作者: 阿登20 | 来源:发表于2020-07-05 21:55 被阅读0次
字符串方法:
一、查找和替换
二、判断类型,返回要么True,要么False
三、大小写转换
四、文本对齐
五、去除空白符:空格 \n \t \r
六、拆分和拼接

字符串方法

一、查找和替换

01 find查找字符串方法,查找str在开始位置结束位置的索引,找不到会返回-1

  • 语法

    str.find(str,start=0,end=len(str))
    start:默认是0,0是索引
    end:默认是字符串整个长度
    返回是查找的字符串最低的索引, 如果找不到就返回 -1
             
    
  • 案例 :info = "abd eeae张三656"

    info = "abd eeae张三656"
    print(info.find("eea")) # 不指定范围表示默认在整个字符串中查找
    print(info.find("eea",2))  # 表示从索引2开始找,直到字符串最后一位
    print(info.find("eea",3,4)) #表示从索引3开始找,到索引4结束.和切片差不多取头不取尾,所以索引4不找,返回-1
    print(info.find("eea",8))   # 从索引8开始找,找不到返回-1
    
    

结果:

4
4
-1
-1

02 rfind方法和find方法类似,找出字符串的最高索引,找不到返回 -1

  • 语法:

    str.rfind(str,start=0,end=len(str))
    start:默认是0,0是索引
    end:默认是字符串整个长度
    返回是查找的字符串最高的索引, 如果找不到就返回 -1
    
  • 案例

    # rfind方法 跟find类似找出最高索引
    print(info.rfind("e"))  # 不指定范围表示默认在整个字符串中查找
    print(info.rfind("e",5)) # 从索引5开始找,直到字符串末尾
    print(info.rfind("e",7,10)) # 从索引7-10这个范围找,10索引不找
    print(info.rfind("e",8))  # 从索引8开始找,找不到返回 -1 
    

结果:

7
7
7
-1

03 index跟find类似,不过找不到会报错,一般要慎用。

  • 语法

    str.index(str,start=0,end=len(str))
    start:默认是0,0是索引
    end:默认是字符串整个长度
    返回是查找的字符串最低的索引, 如果找不到会报错
    
  • 案例:

    str1 = "abc def ger"
    print(str1.index("e"))
    print(str1.index("e",2))
    print(str1.index("e",1,9))
    print(str1.index("m"))  # 找不到会报错:ValueError: substring not found
    

结果:

5

5

5

ValueError: substring not found

04 rindex,找出字符串的最高索引,找不到同样会报错!

  • 语法

    str.index(str,start=0,end=len(str))
    start:默认是0,0是索引
    end:默认是字符串整个长度
    返回是查找的字符串最高的索引, 如果找不到会报错
    
  • 案例

    # rindex 找出字符串的最高索引,找不到会报错
    str1 = "abc def ger"
    
    print(str1.rindex("e"))
    print(str1.rindex("e",2,10))
    print(str1.rindex("e",10))  # ValueError: substring not found
    

结果:

9
9
ValueError: substring not found

05 startswith,检查字符串是否是以指定子字符串开头,返回True or False

  • 语法

    str.startswith(substr, start=0,end=len(string))
    
  • 案例

    str_1 = "this is string example....wow!!!"
    
    print(str_1.startswith("this"))  # 字符串是否以 this 开头
    print(str_1.startswith("string", 8))  # 从索引8开始在字符串 开头是否是string开头
    print(str_1.startswith("this", 2, 4))  # 从索引2-4在字符串 是否以this开头
    

结果:

True
True
False

06 endswith,检测字符串是否以指定子字符串结束,是返回true,不是返回false.

  • 语法

  • str.endswith(substr, start=0,end=len(string))
    

    案例

    str_2 = "love python 100"
    print(str_2.endswith("100"))
    print(str_2.endswith("100", 3))
    print(str_2.endswith("10"))
    

结果:

True
True
False

07 replace 指定子字符串替换为另一个字符串,并且返回结果。

  • 语法

    str.replace(old, new[, count])
    old需要替换的子字符串,new新的子字符串。
    count是可选参数。没有的时,表示替换所有。
    count这个参数出现时,表示替换次数最多count次。
    
  • 案例

    name = "this is adeng"
    new_name = name.replace("adeng", "阿登") # 返回在结果被new_name接受原字符串不变
    print(name)  
    print(new_name)
    

结果:

this is adeng
this is 阿登
  • 案例

    name = "this is adeng"
    
    print(new_name.replace("is", "en"))  # 可选参数count没有时,表示替换所有
    print(new_name.replace("is", "en",1))  # 这里表示最多替换一次
    print(new_name.replace("ios", "en",1)) # 如果old这个子字符串没有,那么就不替换
    

结果:

then en 阿登   
then is 阿登
this is 阿登

08 count统计子字符串出现的次数.返回int

  • 语法

    语法: str.count(substr, beg=0,end=len(string))
    start:默认是0,0是索引
    end:默认是字符串整个长度
    
  • 案例

    info = "ooodajfklajfajj"
    
    print(info.count("a"))  # 统计字符a在次数
    print(info.count("a",5)) # 索引5开始统计
    print(info.count("a",6,10)) # 索引6到10索引这个范围在统计,但是索引10取不到
          
    

结果:

3
2
1

二、判断类型,返回要么True,要么False

01 isalnum,是否是由字母组成或数字组成或数字加字母组成 True,否则返回 False。

  • 案例

    print("带有特殊符号的字符串:", "abd!".isalnum()) 返回 False
    print("全是字母组成的字符串:", "abd".isalnum())  返回 True
    print("全是数字组成的字符串:", "4214321421".isalnum())  返回 True
    print("字母数字混合组成的:", "abdMYY2313213".isalnum())   返回  True
    print("字母数字汉子混合组成的:", "abdMYY2313213".isalnum())   返回  True  # 这里要重视
    

02 isalpha,至少有一个字符并且所有字符都是字母或汉字则返回 True,否则返回 False

  • 案例
print("带有特殊符号的字符串:", "abd!".isalpha())
print("字母和数字组成的字符串:", "abd213213".isalpha())
print("全数字组成的字符串:", "213213".isalpha())
print("全汉字组成的字符串:", "发发嘎嘎嘎".isalpha())
print("汉字和字母组成的字符串:", "发发嘎daaw嘎嘎".isalpha())
print("带空格的字符串:", "发发嘎嘎嘎 ".isalpha())

结果:

带有特殊符号的字符串: False
字母和数字组成的字符串: False
全数字组成的字符串: False
全汉字组成的字符串: True
汉字和字母组成的字符串: True
带空格的字符串: False

03 isdigit,字符串只包含数字则返回 True 否则返回 False

  • 案例
# isdigit 字符串只包含数字则返回 True 否则返回 False

print("带空格在数字:","123132 ".isdigit())   # 返回 False
print("带小数点的数字:","123132.".isdigit())  # 返回 False
print("只有数字:","4234234".isdigit())       # 返回 True

04 isspace,检查字符串只包含空白符.空白符:空格 \r \n \t

  • 案例
print("  \t  \n \r".isspace())   # True
print("  \t  \n \rdada11".isspace())  # False

05 isdecimal,检查字符串只包含数字,正整数才行

  • 案例

    print("小数字符串:","54.5".isdecimal()) # False
    print("带汉字:","发送".isdecimal())     # False
    print("负数:","-100".isdecimal())      # False
    print("正整数:","5".isdecimal())   # True
    str.isdecimal () 与str.isdigit()的区别
    str.isdecimal() 函数只对十进制数返回 True,同时函数 str.isdigit() 对其他 unicode 支持的字符返回 True
    

06 isnumeric,包含数字则返回 True. 全角数字 汉字数字

  • 案例

    # isnumeric,包含数字则返回 True. 全角数字 汉字数字
    print("32141".isnumeric())
    #s = '²3455'
    s = '\u00B23455'
    print(s.isnumeric())
    # s = '½'
    s = '\u00BD'
    print(s.isnumeric())
    
    a = "\u0030" #unicode for 0
    print(a.isnumeric())
    
    b = "\u00B2" #unicode for ²
    print(b.isnumeric())
    
    c = "10km2"
    print(c.isnumeric())
    

结果:

True
True
True
True
True
False

07 istitle,单词首字母大写,其他小写

  • 案例

    print("单词首字母都大写:","This Is String Example...Wow!!!".istitle())
    print("单词首字母都大写,部分单词剩余部分未小写:","THis Is String Example...Wow!!!".istitle())
    print("第一个单词首字母大写,其他单词小写:","This is string example....wow!!!".istitle())
    

结果:

单词首字母都大写: True
单词首字母都大写,部分单词剩余部分未小写: False
第一个单词首字母大写,其他单词小写: False
 

08 islower和 isupper,检查字符串是否全部小写或者大写

  • 案例

    # 检查小写 islower
    print("This is string example....wow!!!".islower())
    print("this is string example....wow!!!".islower())
    
    # isupper 检查大写
    print("THIS IS STRING EXAMPLE....WOW!!!".isupper())
    

结果:

False
True
True

三、大小写转换

01 lower,转换成小写

  • 案例

     >>> "DFAGAGAGA".lower()
     'dfagagaga
    

02 upper转成大写

  • 案例

    >>> "this".upper()
    'THIS'
    

03 title 每个单词首字母转换成大写

  • 案例

    >>> "This is string example....wow!!!".title()
    'This Is String Example....Wow!!!'
    

04 capitalize() 把字符串第一个字母转化为大写

  • 案例

    >>> "this is string example....wow!!!".capitalize()
    'This is string example....wow!!!'
    

05 swapcase() 大小写互换

  • 案例

    >>> "fdafafaMMHJOIH".swapcase()
    'FDAFAFAmmhjoih'
    

四、文本对齐

01 center,返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格

  • 语法

    str.center(width, fillchar)
    width int类型  宽度
    fillchar 要填充的字符
    
  • 案例

    print("阿登帅哥".center(100, "+"))
    center是居中对齐,100表示宽度, 字符串 阿登帅哥不满足100宽度时,用 +两端填充知道满足宽度100
    

结果:

+++++++++++++++++++++++++++阿登帅哥++++++++++++++++++++++++++++++++++

02 ljust,左对齐,参数和center一致

03 rjust,右对齐,参数和center一摸一样

  • 案例

    # ljust() 左对齐,参数和center一摸一样
    print("阿登帅哥".ljust(50, "="))
    
    # rjust 右对齐,参数和center一摸一样
    
    print("阿登帅哥".rjust(50, "="))
    

结果:

阿登帅哥==============================================
==============================================阿登帅哥

五、去除空白符:空格 \n \t \r

01 strip lstrip rstrip,默认移除空白符

  • strip 去除字符串两端在空白符,场景一般用于用户注册

  • lstrip 去除字符串左边在空白符,返回一个新字符串

  • rstrip 去除字符串右边在空白符

  • 案例

    # strip 去除两端的空白符,返回一个新的字符串
    
    str0 = '  Python! !*   '
    
    # 默认移除空白符
    print("strip去除两端空白符:",str0.strip())
    # 指定移除两端多个字符,知道条件不满足返回新字符串
    print("strip指定移除两端多个字符:",str0.strip(" *!"))
    
    # lstrip 移除字符串左边的空白符
    
    print("lstrip移除左边的空白符:", str0.lstrip())
    
    # lstrip 指定移除左边多个满足条件的字符,返回新字符串
    
    print("lstrip指定移除多个字符:", str0.lstrip(" Py"))
    
    # rstrip 移除字符串右边的空白符或指定的字符,道理同lstrip
    
    print("rstrip右边的空白符:", str0.rstrip())
    
    # rstrip 指定移除字符串右边多个字符
    
    print("rstrip指定移除右边的字符空格*!:", str0.rstrip(" *!"))
    

结果:

strip去除两端空白符: Python! !*
strip指定移除两端多个字符: Python
lstrip移除左边的空白符: Python! !*   
lstrip指定移除多个字符: thon! !*   
rstrip右边的空白符:   Python! !*
rstrip指定移除右边的字符空格*!:   Python

六、拆分和拼接

01 split分割字符串

  • 语法

    str.split(str,num)如果第二个参数 num 有指定值,则分割为 num+1 个子字符串
     str 参数表示用什么去分割,默认包含 (空格 \r \n \t)
     num 默认为 -1,表示分割所有。当num指定值时,分割成列表在元素为num+1个 子字符串元素
    
  • 案例

    >>> a = "to be or not to be"
    >>> a.split()   # 不写分隔符,用空白符去分隔包含 空格 \n \t \r
    ['to', 'be', 'or', 'not', 'to', 'be']
    >>> a.split('be')
    ['to ', ' or not to ', ''
    >>> a.split('be', 1) # 指定分隔次数,num指定一个int值就行,比如这里指定分隔1次
     ['to ', ' or not to be']
    
  • 案例2 url分隔,获取图片格式,图片名称

    url = "http://www.baidu.com/python/image/123456.jpg"
    #以“.” 进行分隔
    path =url.split(".")
    print(path)
    以上输出结果:获取一个文件的后缀格式的方法
    
    ['http://www', 'baidu', 'com/python/image/123456', 'jpg']
    以 / 进行分隔:
    
    ['http:', '', 'www.baidu.com', 'python', 'image', '123456.jpg']
    我们在学习 python 爬虫的时候例如需要保存图片,图片名称的获取,可以依照下列方法:
    
    picture =url.split("/")[-1]
    输出结果:
    
    '123456.jpg'
    
    

02 splitlines按照(\r,\r\n,\n分隔,返回一个包含各行的作为元素的列表

  • 语法

    str.splitlines(keepends=False)
    keepends默认为False,不保留换行符,为True表示保留换行符
    
  • 案例

    tl = 'ab c\n\nde fg\rkl\r\n'
    
    print(tl.splitlines())  # 默认False,不保留换行符
    # 上面输出结果
    # ['ab c', '', 'de fg', 'kl']
    print(tl.splitlines(True))
    #输出结果
    # ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
    

03 rsplit 做右到左分割,跟split相反

  • 案例

    url = "http://www.baidu.com/python/image/123456.jpg"
    
    pp = url.split(".",1)
    ppp = url.rsplit(".",1) # 如果要获取一个路径的最后文件后缀可以反向分隔
    print(pp,ppp,sep="\n")
    # 结果为
    ['http://www', 'baidu.com/python/image/123456.jpg']
    ['http://www.baidu.com/python/image/123456', 'jpg']
    

04 partition,分隔符讲字符串分隔成三个子字符串的元组

  • 语法

    str.partition(sep)  sep分隔符,分割成三部分组成1个元祖
    (分隔符左边字符串,分隔符,分隔符右边字符串)
    
  • 案例

    url_1 = "www.baidu.com"
    print(url_1.partition("baidu"))
    # ('www.', 'baidu', '.com')
    
    # 如果找不到分隔符,返回原来在字符串和两个空字符串
    print(url_1.partition("p"))
    # ('www.baidu.com', '', '')
    
  • rpartition(sep),跟partition类似只是从右边开始找

05 join,序列中的元素以指定的字符连接生成一个新的字符串

  • 语法

    str.join(sep)
    str用来拼接可迭代对象在元素,组成1个新在字符串
    sep 的元素必须是字符串,不然要报错
    
  • 案例

    # 可迭代对象 的元素不是字符串会报错
    a = ["adeng",1]
    print("".join(a)) #TypeError: sequence item 1: expected str instance, int found
    # 列表a中的元素 1是int类型不是字符串所以报错了
    
  • 迭代对象可以是 字符串 列表 元组 集合 字典

    # 迭代对象是字符串
    print("_".join("我们爱中国"))
    
    # 迭代对象是一个列表
    print("".join(["p",'e','n']))
    
    # 迭代对象是一个元组
    print("".join(("p",'e','n')))
    
    # 迭代对象是一个字典,拼接的是字典的key
    print('-'.join({"name1":"joy","name2":"john","name3":"jerry"}))
    #结果
    '''
    我_们_爱_中_国
    pen
    pen
    name1-name2-name3
    
    '''
    
  • 案例 join 方法的确是程序中字符串与列表相互转换的很好用的工具
# 案例将1个手输入的字符串,倒叙排。这里我们用join方法
# 方法1
str_n = input("请输出一串字符串:\n")
# 定义一个空列表
list_one = []

for i in list(range(len(str_n)-1,-1,-1)): # 倒叙取出索引
    list_one.append(str_n[i])
print(list_one)
print("".join(list_one))

# 方法2:
"""
字符串用循环索引倒着取值,加入到一个空列表,再用空字符串join方法拼接得到一个倒叙字符串

"""
list_one2 = []
str_m = input("请输出一串字符串:\n")
num_1 = len(str_m) -1
while (num_1 >=0):
    
    list_one2.append(str_m[num_1])
    # 控制循环次数 每次-1
    num_1 -= 1             # 也可以用break 如果num_1 == 0,就break跳出循环
    
print("".join(list_one2))
# 这里完全可以用列表推导式简化代码,之后我们将到列表会演示的
'''

请输出一串字符串:
fasfafj额外发886712
217688发外额jfafsaf

'''

相关文章

网友评论

      本文标题:py05_字符串内置方法

      本文链接:https://www.haomeiwen.com/subject/qscvqktx.html