您的位置:首页 > 编程语言 > Python开发

Python字符串操作全集(四)查询、索引和替换

2020-07-14 06:35 821 查看

字符串的查询、索引、替换

  • 索引
  • 替换
  • 查询

    count(sub,start,end)

    返回sub在字符串中出现的次数,start和end表示范围

    temp='good good study'
    print('2-10范围‘o’出现的次数:',temp.count('o',2,10))

    输出结果:
    2-10范围‘o’出现的次数: 3

    startwith(sub,start,end)

    检查字符串是否以sub开头,是则返回True,否则返回False。start和end指定范围

    temp='祖国的花朵'
    print(temp.startswith('祖国'))

    *输出结果:
    True

    endwith(sub,start,end)

    检查字符串是否以sub字符串结尾,是返回True,否返回False。start,end表示范围。

    temp='祖国的花朵'
    print(temp.endswith('花朵'))

    *输出结果:
    True

    isalnum()

    如果字符串所有的字符都是字母和数字则返回True,否则返回False

    temp4='我是编程爱好者,programer'
    temp5='program1223'
    print(temp4.isalnum())
    print(temp5.isalnum())

    *输出结果:
    False
    True

    isalpha()

    如果字符串所有的字符都是字母则返回True,否则返回False

    temp6='teacher'
    temp7='丽丽teacher123'
    print('temp6:',temp6.isalpha())
    print('temp7:',temp7.isalpha())

    *输出结果:
    temp6: True
    temp7: False
    注: 中文需要先编码,否则无法识别中文

    isdecimal()

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

    temp7='334455'
    print(temp7.isdecimal())

    *输出结果:
    True

    isdigit()

    如果字符串只包含数字字符则返回True,否则返回False

    temp7='334455'
    print(temp7.isdigit())

    *输出结果:
    True

    索引

    find(sub,start,end)

    检查sub是否包含在字符串中,是则返回索引值,否则返回-1

    temp='good good study'
    print('‘od’索引:',temp.find('od'))  #有,返回索引
    print('‘od’索引:',temp.find('xo'))  #无,返回-1

    *输出结果:
    ‘od’索引: 2
    ‘od’索引: -1

    rfind(sub,start,end)

    从右边开始检查sub是否包含在字符串中,是则返回索引值,否则返回-1

    temp='good good study'
    print('rfind从右边查找od:',temp.rfind('od'))
    print('rfind从右边查找ox:',temp.rfind('ox'))

    *输出结果:
    rfind从右边查找od: 7
    rfind从右边查找ox: -1

    index(sub,start,end)

    检查sub是否包含在字符串中,是则返回索引值,否则返回异常

    temp='good good study'
    print(temp.index('od',0,12))  #有,返回索引
    print(temp.index('xo',0,12))  #无,返回异常

    *输出结果:
    2
    ValueError: substring not found

    rindex(sub,start,end)

    从右边开始检查sub是否包含在字符串中,是则返回索引值,否则返回异常

    temp='good good study'
    print('rindex查找:',temp.rindex('od',0,12))  #有,返回索引
    print(temp.rindex('xo',0,12))  #无,返回异常

    *输出结果:
    rindex查找:7
    ValueError: substring not found

    替换

    replace(old,new,count)

    把字符串中的old子字符串替换成new子字符串。如果指定count,则替换不超过count次

    temp18='pig dog cat fish fish'
    temp19=temp18.replace('fish','duck',1)
    print(temp19)

    *输出结果:
    pig dog cat duck fish

    translate(table)

    根据table的规则(可以由str.maketrans(‘a’,‘b’)定制)转换字符串中的字符

    temp18='pig dog cat fish fish'
    temp20=temp18.translate(str.maketrans('i','a'))
    print(temp25)

    *输出结果:
    pag dog cat fash fash

    内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: 
    相关文章推荐