• python 之字符串操作函数


    a = 'ihoewpgDEVbbraVEecddg'

    字母的处理

    print(a.upper())    #字符串全部改为大写
    print(a.lower())      #字符串全部改为小写
    print(a.swapcase())   #大小写互换
    print(a.capitalize())    #首字母大写其余全部小写
    print(a.title())       # 同上

     格式化相关

    print(a.ljust(30))    #获取固定长度30字符,左对齐,不够的用空格补齐
    print(a.rjust(30))    #获取固定长度30字符,右对齐,不够的用空格补齐
    print(a.center(30))   #获取固定长度30字符,居中,不够的用空格补齐
    print(a.zfill(30))    #获取固定长度30字符,右对齐,不够的用0补齐

     字符串搜索

    print(a.find('o',0,10))     # 搜索指定字符o ,范围从下标0到下标10  搜索不到返回-1
    print(a.index('d',0,20))    # 搜索指定字符d,范围从下标0到下标20   搜索不到会报错
    print(a.rfind('d'))         #从右边开始查找
    print(a.count('d'))         #统计指定字符d出现的次数

     字符串替换

    print(a.replace('e','ww',2))  # 将字符中的e替换为ww ,替换次数为2次

     字符串去空格及去指定字符

    print(a.strip('i'))       #去掉字符串两边的空格或字符
    print(a.lstrip('i'))      #去掉字符串左边的空格或字符
    print(a.rstrip('i'))      #去掉字符串右边的空格或字符
    print(a.split('E'))       #按字符或按空格分割字符串为数组

     字符串判断

    print(a.startswith('i'))   #判断是否以i开头
    print(a.endswith('i'))     #判断是否以i结尾
    print(a.isalnum())         #判断字符串是否全为字母或数字
    print(a.isalpha())         #判断字符串是否全为字母
    print(a.isdigit())         #判断字符串是否全为数字
    print(a.islower())         #判断字符串是否全为大写
    print(a.isupper())         #判断字符串是否全为小写
    print(a.istitle())         #判断字符串首字母是否大写
    print(a.isspace())         #判断字符是否为空格

    使字符串以倒序显示

    for i in range(21,-1,-1):
        print(a[i])
    #或
    for i in range(-1,-23,-1):
        print(a[i])

     拓展

    a = [x for x in a]
    for i in range(len(a)//2):
        c = a[i]
        b = a[-(i+1)]
        a[i] = b
        a[-(i + 1)] = c
    a = ''.join(a)
    print(a)

  • 相关阅读:
    [LeetCode] 456. 132 Pattern
    [LeetCode] 606. Construct String from Binary Tree
    [LeetCode] 536. Construct Binary Tree from String
    [LeetCode] 925. Long Pressed Name
    [LeetCode] 652. Find Duplicate Subtrees
    [LeetCode] 743. Network Delay Time
    [LeetCode] 1209. Remove All Adjacent Duplicates in String II
    [LeetCode] 1047. Remove All Adjacent Duplicates In String
    [LeetCode] 1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
    [LeetCode] 859. Buddy Strings
  • 原文地址:https://www.cnblogs.com/wbf980728/p/14006854.html
Copyright © 2020-2023  润新知