day10字符串相关方法和格式化

本文详细介绍了Python字符串的一些常用方法,如join用于连接序列成字符串,split按指定字符切分字符串,replace替换字符串中的指定部分,strip去除字符串两侧的空白字符。此外,还讲解了find、index、count、endswith、startswith等方法,以及字符串格式化的方法和注意事项。这些方法在处理字符串时非常实用。
摘要由CSDN通过智能技术生成

字符串相关方法

字符串.xxx()

join

字符串.join(序列) - 将序列中的元素用指定的字符串拼接在一起,形成一个新的字符串(序列中的元素必须是字符串)

list1 = ['后裔','王昭君','鲁班七号','孙悟空']
result = ''.join(list1)
print(result)    # 后裔王昭君鲁班七号孙悟空

result = '+'.join(list1)
print(result)    # 后裔+王昭君+鲁班七号+孙悟空

result = ' and '.join(list1)
print(result)    # 后裔 and 王昭君 and 鲁班七号 and 孙悟空

如果需要join的序列中的元素不是字符串,就想办法把它的元素变成字符串再join

nums = [23,45,67,89,45]
# '2345678945'
result = ''.join([str(i) for i in nums])   # ['23', '45', '67', '89', '45']
print(result)     # 2345678945

result = '*'.join('abc')
print(result)     # a*b*c
split
  1. 字符串1.split(字符串2) - 将字符串1中所有的字符串2作为切割点对字符串进行切割,返回包含切割后每一小段对应的字符串的列表

    str1 = 'abcmn123mnkplmn##'
    result = str1.split('mn')
    print(result)       # ['abc', '123', 'kpl', '##']
    
    str1 = 'mnabcmnmn123mnkplmn##mn'
    result = str1.split('mn')
    print(result)       # ['', 'abc', '', '123', 'kpl', '##', '']
    
  2. 字符串1.split(字符串2, N) - 将字符串1中前N个字符串2作为切割点为字符串1进行切割

    str1 = 'abcmn123mnkplmn##'
    result = str1.split('mn', 2)
    print(result)
    
replace
  1. 字符串1.replace(字符串2,字符串3) - 将字符串1中所有的字符串2都替换成字符串3

    str1 = 'mnabcmnmn123mnkplmn##mn'
    result = str1.replace('mn','ABC')
    print(result)    # ABCabcABCABC123ABCkplABC##ABC
    
    result = str1.replace('mn','')
    print(result)    # abc123kpl##
    
  2. 字符串1.replace(字符串2,字符串3,N) - 将字符串1中前N个字符串2替换成字符串3

    result = str1.replace('mn','AB',3)
    print(result)    # ABabcABAB123mnkplmn##mn
    
strip
  1. 字符串.strip() - 删除字符串左右两端的空白字符

    str1 = '\n\t    小明\n\t    '
    print(str1)
    """
    
    	    小明
    	    
    """
    
    result = str1.strip()
    print(result)     # 小明
    
    str1 = '/小明/'    # 删除字符串左右两端的'/'
    result = str1.strip('/')
    print(result)     # 小明
    
  2. 字符串.rstrip() - 删除字符串右边的空白字符
    字符串.lstrip() - 删除字符串左边的空白字符

find、index
  1. 字符串1.find(字符串2) - 获取字符串1中字符串2第一次出现的位置(以0开始的下标值返回),如果字符串2不存在返回-1

    str1 = 'How are you? I am fine, thank you !and you ?'
    print(str1.find('you'))    # 8
    print(str1.find('abc'))    # -1
    
  2. 字符串1.index(字符串2) - 获取字符串1中字符串2第一次出现的位置(以0开始的下标值返回),如果字符串2不存在报错!

    str1 = 'How are you? I am fine, thank you !and you ?'
    print(str1.index('you'))   # 8
    print(str1.index('abc'))   # ValueError: substring not found
    
  3. 字符串1.find(字符串2,开始下标,结束下标) - 获取字符串1中指定范围内字符串2第一次出现的位置

    str1 = 'How are you? I am fine, thank you !and you ?'
    print(str1.find('you', 10))     # 30
    print(str1.find('you', 10, 26))     # -1
    
  4. 字符串1.index(字符串2,开始下标,结束下标) - 获取字符串1中指定范围内字符串2第一次出现的位置

  5. rfind、rindex

    str1 = 'how are you? I am fine, thank you! and you?'
    print(str1.rfind('you'))     # 39
    
其他方法
  1. casefold

    print('abcMN233'.casefold())     # abcmn233
    
  2. center、rjust、ljust、zfill

    str1 = 'abc'
    print(str1.center(7, '+'))          # '++abc++'
    print(str1.rjust(7, '*'))           # '****abc'
    print(str1.ljust(7, '&'))           # 'abc&&&&'
    print(str1.zfill(7))                # '0000abc'
    
  3. count

    str1 = 'mnabcmnmn123mnkplmn##mn'
    print(str1.count('a'))              # 1
    print(str1.count('mn'))             # 6
    
  4. endwith、startwith

    str1 = 'mnabcmnmn123mnkplmn##mn'
    print(str1.endswith('abc'))        # False
    print(str1.endswith('#mn'))        # True
    
    print(str1.startswith('ab'))       # False
    print(str1.startswith('mn'))       # True
    
  5. format

    name = '小明'
    age = 18
    # 'xxx今年xx岁!'
    result = str.format('{}今年{}岁!', name, age)
    print(result)             # 小明今年18岁!
    
    result = str.format('{0}今年{1}岁!{0}', name, age)
    print(result)             # 小明今年18岁!小明
    
    
    result = '{name}今年{age}岁!'.format_map({'name': '小明', 'age': 18})
    print(result)             # 小明今年18岁!
    
  6. isdecimal、isdigit、isnumeric

    print('2323'.isdecimal())                   # True
    print('232a3'.isdecimal())                  # False
    print('23239一'.isdecimal())                # False
    print('23211'.isdigit())                    # True
    print('232+11'.isdigit())                   # False
    print('2323一'.isdigit())                    # False
    print('2323'.isnumeric())                    # True
    print('232a3'.isnumeric())                   # False
    print('2323一十百万Ⅱ拾Ⅲ'.isnumeric())         # True
    
    str1 = '722实ss际上Mn飞机22-2233=+集H合289'
    for x in str1:
        # '0' <= x <= '9' or 'a' <= x <= 'z' or 'A' <= x <= 'Z'
        if x.isdigit() or x.isupper() or x.islower():
            print(x)  # 722ssMn222233H289
    
    print('hjas'.islower())    # True
    print('x'.islower())       # True
    
    print('JKSS'.isupper())    # True
    print('M'.isupper())       # True
    
    print('a'.upper())         # A
    print('M'.lower())         # m
    
  7. maketrans、translate

    str1 = '1727283112闪烁2nsnk2'
    # '一七二七二八三一一二'
    # 创建一个映射表
    table = str.maketrans('1234567890', '一二三四五六七八九零')    # 1-一;2-二;3-三;...
    # 根据映射表的对应的关系替换字符串中的相关字符
    result = str1.translate(table)
    print(result)    # 一七二七二八三一一二闪烁二nsnk二
    
    # 星期1  -> 星期一
    # 星期7  -> 星期天
    str1 = '星期7'
    table = str.maketrans('1234567', '一二三四五六天')
    print(str1.translate(table))    # 星期天
    

字符串格式化

如何解决字符串内容变化的问题?

字符串拼接
name = '小明'
age = 18
message = name + '今年' + str(age) + '岁!'
print(message)            # 小明今年18岁!

money = 15000
# xxx今年xx岁!月薪:xxxx.xx元
message = name + '今年' + str(age) + '岁!月薪:' + str(money) + '元'
print(message)            # 小明今年18岁!月薪:15000元
格式字符串

语法:
包含一个或者多个格式占位符的字符串 % (数据1,数据2,数据3,…)

说明:()中的数据必须和前面字符串中的占位符一一对应。如果只需要一个数据,那么()可以省略

常用的字符串占位符:

  1. %s - 可以给任意类型的数据占位(字符串占位符)

    result = '%s%s%s' % ('abc',12,[10,20])
    print(result)          # abc12[10, 20]
    
  2. %d - 只能给数据占位(整数占位符)

    result = '%d-%d' % (12,2.34)
    print(result)          # 12-2
    
  3. %f - 只能给数字数据占位(浮点数占位符,默认保留六位小数)

    result = '%f-%f' % (2.3,34)
    print(result)          # 2.300000-34.000000
    
  4. %.Nf - 只能给数字数据占位(保留N位小数)

    result = '%.2f-%.2f' % (2.3,34)
    print(result)          # 2.30-34.00
    
message = '%s今年%d岁!月薪:%f元' % (name,age,money)
print(message)         # 小明今年18岁!月薪:15000.000000元
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值