广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python -- str 类
  • 648
分享到

Python -- str 类

Pythonstr 2023-01-31 07:01:33 648人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

python str类常用方法:class str(object):     def capitalize(self):   # 全部字母变小写只有首字母变大写;                         >>> t


python str类常用方法:

class str(object):

 

    def capitalize(self):   # 全部字母变小写只有首字母变大写;

                         >>> test = 'Python'

                         >>> test.capitalize()

                         'Python'

    def casefold(self): # 全部字母变小写;

                            

                        >>> test = 'PYTHON'

                        >>> test.casefold()

                        'python'


    def center(self, width, fillchar=None): # 内容居中,width 总长度,fillchar 空白处

                                                填充内容,默认空;

                        >>> test

                        'PYTHON'

                        >>> test.center(20,'*')

                        '*******PYTHON*******'


    def count(self, sub, start=None, end=None):  # 计算字符在字符串中出现的次数,

                                                    支持可选长度;

                        >>> test = 'python,python'

                        >>> test.count('py',0,10)

                            2

    def  decode(self, encoding='utf-8', errors='strict'):  # 解码

                        >>> test1=test.encode('gbk')

                        >>> test1

                        b'python,python'

                        >>> test1.decode('gbk')

                        'python,python'

                 

    def encode(self, encoding='utf-8', errors='strict'):  # 编码

                        >>> test

                        'python,python'

                        >>> test.encode('gbk')

                        b'python,python'


    def endswith(self, suffix, start=None, end=None):  # 在字符串中以指定元素结尾则

                                                        返回布尔值真,否则返回假;

                        >>> test = 'python,[1,2]'

                        >>> test.endswith('[1]')

                            False

                        >>> test.endswith('[2]')

                            False

                        >>> test.endswith('2]')

                            True


    def expandtabs(self, tabsize=8): # 返回字符串的特定格式化,所有的tab被一个或多个

                                        空格代替,默认8个空格;

                        >>> test = '1\t23\t45\t6'

                        >>> test.expandtabs()

                        '1       23      45      6'

                        >>> test.expandtabs(2)

                        '1 23  45  6'

    def find(self, sub, start=None, end=None):  # 返回sub在str中所发现的最小索引

                                                如果为发现则返回-1;

                        >>> test = 'python,linux,python'

                        >>> test.find('y')

                        1

                        >>> test.find('a')

                        -1

    def fORMat(*args, **kwargs):  # 字符串格式化。使用该方法的字符串能够使用括号{}

                                    包含的替换域,每个替换域或者使用位置编号,或者

                                    使用变量名,返回字符串的拷贝,并且所有都被替换

                        >>> test = 'name : {0}, pwd : {1}'

                        >>> test.format('lihongye','pwd1')

                        'name : lihongye, pwd : pwd1'

                        >>> test = 'name : {x}, pwd : {y}'

                        >>> test.format(x='lihongye',y='pwd1')

                        'name : lihongye, pwd : pwd1'


    def format_map(self, mapping):  #


    def index(self, sub, start=None, end=None): # 同find,不同是如果没有则返回ValueError;

                        >>> test = 'python,linux,python'

                        >>> test.index('a')

                        Traceback (most recent call last):

                         File "<stdin>", line 1, in <module>

                        ValueError: substring not found

                        >>> test.index('p')

                        0


    def isalnum(self):    # 如果是数字、字母则返回True,否则返回False;

                        >>> test = 'x'

                        >>> test.isalnum()

                        True

                        >>> test = 'xy'

                        >>> test.isalnum()

                        True

                        >>> test = '*'

                        >>> test.isalnum()

                        False


    def isalpha(self):   # 如果字符串中所有字符都是字母,则返回True,否则返回False;


    def isdecimal(self):#如果字符串中所有字符都是十进制数字,则返回True,否则返回False;


    def isdigit(self):   # 如果字符串中的所有字符都是数字,则返回True,否则返回False;


    def isidentifier(self): #如果字符串中的所有字符都是有效的变量名,则返回True

                              否则返回False;


    def islower(self):   # 字符串中的所有字符都是小写,则返回True,否则返回False;


    def isnumeric(self):  # 字符串中所有字符都是数字字符,则返回True,否则返回False;


    def isprintable(self):  # 字符串为空或者为数字,则返回True,否则返回False;


    def isspace(self):  #  如果字符串全为空格,则返回True,否则返回False;

                        >>> test = 'print'

                        >>> test.isspace()

                        False

                        >>> test = ''

                        >>> test.isspace()

                        False

                        >>> test = '    '

                        >>> test.isspace()

                        True


    def istitle(self):  # 如果字符串是首字母大写,则返回True,否则返回False;

                        >>> test = 'print'

                        >>> test.istitle()

                        False

                        >>> test = 'Print'

                        >>> test.istitle()

                        True


    def isupper(self): # 如果字符串中所有字符全为大写,则返回True,否则返回False;


    def join(self, iterable): #  将含有字符串的列表以特定字符串拼接起来形成字符串;

                        >>> test_list = ['1','2','3','4',]

                        >>> '_'.join(test_list)

                        '1_2_3_4'

    def ljust(self, width, fillchar=None):  #返回一个适合长度的字符串,使用定义的

                                            字符串向右填充,默认空白;

                       >>> test

                        'python'

                       >>> test.ljust(10,'*')

                        'python****'


    def lower(self):  # 将所有字符串变小写;


    def lstrip(self, chars=None):  # 移除字符串左侧空格;

                        >>> test = '  PYTHON  '

                        >>> test.lstrip()

                        'PYTHON  '


    def partition(self, sep):  # 从第一个出现的sep开始分离字符串形成三部分:

                                          sep前,sep,sep后

                                如果未找到则返回字符串整体和两个空字符串;

                        >>> test = '1230045600789'

                        >>> test.partition('00')

                        ('123', '00', '45600789')

                        >>> test.partition('a')

                        ('1230045600789', '', '')

    

    def replace(self, old, new, count=None): # 返回一个新的字符串,其中所有的old都被

                                    new代替count用于指定前count个,默认为none全部替换;

                        >>> test

                        '1230045600789'

                        >>> test.replace('0','a',3)

                        '123aa456a0789'

                        >>> test.replace('0','a')

                        '123aa456aa789'


    def rfind(self, sub, start=None, end=None): # 返回sub在str中最后出现的索引号,

                                                找不到返回-1;


    def rindex(self, sub, start=None, end=None): # 返回sub在str中最后出现的索引号,

                                                找不到返回ValueError;


    def rjust(self, width, fillchar=None):  #返回一个适合长度的字符串,使用定义的

                                                字符串向左填充,默认空白;


    def rpartition(self, sep):  #从最后一个出现的sep开始分离字符串形成三部分:

                                            sep前,sep,sep后

                                如果未找到则返回字符串两个空字符串和整体;

                        >>> test = '1230045600789'

                        >>> test.rpartition('00')

                        ('12300456', '00', '789')

                        >>> test.rpartition('a')

                        ('', '', '1230045600789')


    def rsplit(self, sep=None, maxsplit=-1):  # 使用指定的字符分割字符串形成列表,

                                                从右向左开始分割,指定最大分割个数

                                                未指定分割个数则全部按指定全部分割;

                        >>> test

                        '1230045600789'

                        >>> test.rsplit('0',3)

                        ['1230', '456', '', '789']


    def rstrip(self, chars=None): #返回末尾被移除的字符串,默认移除空格,

                                            chars表示移除的字符集;

                        >>> test = '  1230045600789   '

                        >>> test.rstrip()

                        '  1230045600789'

                        >>> test.rstrip('89   ')

                        '  12300456007'

    def split(self, sep=None, maxsplit=-1): # 使用指定的字符分割字符串形成列表,

                                                从左向右开始分割,指定最大分割个数

         未指定分割个数则全部按指定全部分割;


    def splitlines(self, keepends=None):  #按行分割,返回一个包含各行作为元素的列表,

                                            如果num指定则仅切片num个行;

                        >>> test = 'test1\ntest2\ntest3\ntest4\n'

                        >>> print(test)

                        test1

                        test2

                        test3

                        test4


                        >>> print(test.splitlines())

                        ['test1', 'test2', 'test3', 'test4']

                        >>> print(test.splitlines(0))

                        ['test1', 'test2', 'test3', 'test4']

                        >>> print(test.splitlines(1))

                        ['test1\n', 'test2\n', 'test3\n', 'test4\n']

                        >>> print(test.splitlines(2))

                        ['test1\n', 'test2\n', 'test3\n', 'test4\n']

                        >>> print(test.splitlines(3))

                        ['test1\n', 'test2\n', 'test3\n', 'test4\n']

                        >>> print(test.splitlines(4))

                        ['test1\n', 'test2\n', 'test3\n', 'test4\n']


    def startswith(self, prefix, start=None, end=None): # 字符串如果以指定字符开头则

                                                        返回True,否则返回False;


    def strip(self, chars=None):  #返回字符串并移除首尾字符,默认空白;


    def swapcase(self):  # 返回字符串并转换所有字符串的大小写;


    def title(self):  # 返回每个单词的首字母大写,其余字母小写;


    def translate(self, table):   # (同maketrans一起使用) ;

    

    def maketrans(self, *args, **kwargs): # 用于创建字符映射的转换表,对于接受两个

                                            参数的最简单的调用方式第一个参数是字符集,

                                            表示需要转换的字符,第二个参数也是字符集

        表示要转换的目标。两个字符集长度相等一一对应;

            maketrans()方法: transname = str.maketrans(inname,outname)

            translate( )    方法:  str.translate(transname)

                        >>> inname = 'aeiou'

                        >>> outname = '12345'

                        >>> transname = inname.maketrans(outname)

                        >>> test = 'this is a out exam'

                        >>> transname = test.maketrans(inname,outname)

                        >>> transname

                        {97: 49, 111: 52, 117: 53, 101: 50, 105: 51}

                        >>> test.translate(transname)

                        'th3s 3s 1 45t 2x1m'


    def upper(self):   # 所有字符都被转换成大写;


    def zfill(self, width):   # 返回一个str 的拷贝,长度为width,左边用0填充,

                                    如果字符串以+、-开头则在其后填充0;

                        >>> test = '-53'

                        >>> test.zfill(6)

                        '-00053'


--结束END--

本文标题: Python -- str 类

本文链接: https://www.lsjlt.com/news/190701.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python -- str 类
    Python str类常用方法:class str(object):     def capitalize(self):   # 全部字母变小写只有首字母变大写;                         >>> t...
    99+
    2023-01-31
    Python str
  • python Str类方法
    #capitalize():字符串首字符大写 string = 'this is a string.' new_str = string.capitalize() print(new_str) #输出:This is a string.  ...
    99+
    2023-01-31
    方法 python Str
  • python学习系列--str类型
    str的内置方法。__contains__()        判断字符串中是否包含某特定字符。等同于'in'关键字。__format__()           字符串格式化。capitalize()             首字母大写。c...
    99+
    2023-01-31
    类型 系列 python
  • python各种类型转换-int,str
    int(x [,base ]) 将x转换为一个整数 long(x [,base ]) 将x转换为一个长整数 float(x ) 将x转换到一个浮点数 complex(r...
    99+
    2023-01-31
    类型 python str
  • Python内建类型str源码学习
    目录引言1 Unicode2 Python中的Unicode2.1 Unicode对象的好处2.2 Python对Unicode的优化3 Unicode对象的底层结构体3.1 PyA...
    99+
    2022-11-11
  • Python内建类型str源码分析
    这篇文章主要讲解了“Python内建类型str源码分析”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python内建类型str源码分析”吧!1 Unicode计算机存储的基本单位是字节,由8...
    99+
    2023-06-30
  • python3.x中str,bytes类
    在研究Python3.x的过程中,遇到的一个纠结了我几天的问题:总是提示“a bytes-like object is required,not 'str' ”在python3.x里增加了bytes类型,并且对str方法进行了修改,让str...
    99+
    2023-01-31
    str bytes
  • python Binary to Str
    相信编码问题困扰了不少coder,最近遇到的一些坑分享给大家。1、通用方法 :decode对应的编码>>> b"abcde" b'abcde' # utf-8 is used here because it is a v...
    99+
    2023-01-31
    python Binary Str
  • python float转str
      if __name__ == '__main__':     a=1.2553435435435     bb="%.3f" % a     print(bb) ...
    99+
    2023-01-31
    python float str
  • python中str与int类型的相互转换
    python中str与int类型的相互转换 1. str转换成int 方法:使用int()函数 # python中str转换成int a='12' b=int(a) # 转换成1...
    99+
    2023-10-11
    python
  • Python基本数据类型之字符串str
    字符串的表示方式 单引号 ' ' 双引号 " " 多引号 """ """"  、 ''' ''' print("hello world") ...
    99+
    2022-11-12
  • 如何进行python str与json类型转换
    这篇文章给大家介绍如何进行python str与json类型转换,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。在写接口测试框架时。避免不了数据类型的转换,比如强制转换string类型,比如转json类型str转json...
    99+
    2023-06-04
  • Python3中的bytes类型和str类型
    目录前言:编码发展的历史bytes和str之间的异同前言: Python 3最重要的新特性之一是对字符串和二进制数据流做了明确的区分。文本总是Unicode,由str类型表示,二进制...
    99+
    2022-11-11
  • Python - 了解bytes、str
        Python3有两种表示字符序列的类型:bytes和str。前者的实例包含原始的8位值,后者的实例包含Unicode字符。    Python2也有两种表示字符序列的类型,分别叫做str和Unicode。与Python3不同的是,s...
    99+
    2023-01-31
    Python bytes str
  • python中unicode 和 str
    python中的str对象其实就是"8-bit string" ,字节字符串,本质上类似java中的byte[]。  而python中的unicode对象应该才是等同于java中的String对象,或本质上是java的char[...
    99+
    2023-01-31
    python unicode str
  • 怎么在Python中利用str()解决类型错误
    怎么在Python中利用str()解决类型错误?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。python有哪些常用库python常用的库:1.requesuts;2.scr...
    99+
    2023-06-14
  • Python源码:str对象
    class str(object):     """     str(object='') -> str     str(bytes_or_buffer[, encoding[, errors]]) -> str        ...
    99+
    2023-01-31
    源码 对象 Python
  • python str转bool方法
    def str_to_bool(str): return True if str.lower() == 'true' else False   ...
    99+
    2023-01-31
    方法 python str
  • python str()如何将参数转换为字符串类型
    str()将参数转换为字符串类型 a = 26 print('我有'+str(a)+'个苹果') 输出:我有26个苹果 Python值被转换成字符串的两种机制 初学Python时可以发现,所有通过Python打...
    99+
    2022-06-02
    python str() 参数转换 字符串类型
  • python中str怎么使用
    Python中str是一种字符串类型的数据结构,用于表示文本信息。可以通过以下方式使用str:1. 创建一个字符串对象:```s =...
    99+
    2023-08-28
    python
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作