str函数(1)

本文介绍了Python中str的一些核心函数,包括center、rjust、ljust、zfill等用于字符串格式化的函数,以及find、rfind、index、rindex用于查找子串的函数,还有split、replace等字符串操作方法。此外,还提到了islower、isupper、isdigit等检查字符串特性的函数,以及upper、lower、lstrip和endswith等实用方法。
摘要由CSDN通过智能技术生成

str的函数

center(text: str, width: int, fillchar=’ ') 返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格

def center(text: str, width: int, fillchar=' '):
    '''

    :param text: 需要操作的字符串
    :param width: 宽度
    :param fillchar: 填充字符;默认为空格
    :return: 填充后的字符串
    '''
    if len(fillchar) != 1:
        eval('TypeError:The fill character must be exactly one character long')  # 填充字符的长度必须正好为一个字符
    length = len(text)
    if length >= width:
        return text
    else:
        width -= length
        width1 = width//2
        if width/2 == width1:
            return fillchar*width1+text+fillchar*width1
        else:
            return fillchar*(width1+1)+text+fillchar*width1

rjsut(text: str, width: int, fillchar=’ ') 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。

def rjsut(text: str, width: int, fillchar=' '):
    '''

    :param text: 需要操作的字符串
    :param width: 宽度
    :param fillchar: 填充字符;默认为空格
    :return: 填充后的字符串
    '''
    if len(fillchar) != 1:
        eval('TypeError:The fill character must be exactly one character long')  # 填充字符的长度必须正好为一个字符
    length = len(text)
    if length >= width:
        return text
    else:
        width -= length
        return fillchar*width+text

ljust(text: str, width: int, fillchar=’ ') 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。

def ljust(text: str, width: int, fillchar=' '):
    '''

    :param text: 需要操作的字符串
    :param width: 宽度
    :param fillchar: 填充字符;默认为空格
    :return: 填充后的字符串
    '''
    if len(fillchar) != 1:
        eval('TypeError:The fill character must be exactly one character long')
    length = len(text)
    if length >= width:
        return text
    else:
        width -= length
        return text+fillchar*width

zfill(text: str, width: int) 返回长度为 width 的字符串,原字符串右对齐,前面填充0

def zfill(text: str, width: int):
    '''

    :param text: 需要操作的字符串
    :param width: 宽度
    :param fillchar: 填充字符;默认为空格
    :return: 填充后的字符串
    '''
    length = len(text)
    if length >= width:
        return text
    else</
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值