美文网首页
Python中关于字符串的操作

Python中关于字符串的操作

作者: 29739ad8e7f7 | 来源:发表于2018-12-20 16:54 被阅读0次

    在Python中,字符串对象本身提供了很多可以操作的方法,我们只需要通过对象去调用方法就可以使用

    讲解案例

    我们先来看看一个字符串对象有哪些可以使用的方法

    声明一个变量并给该变量赋予一个字符串对象
    >>> name = 'xiaoniao'
    >>> dir(name)
     ['__add__',
     '__class__',
     '__contains__',
     '__delattr__',
     '__dir__',
     '__doc__',
     '__eq__',
     '__format__',
     '__ge__',
     '__getattribute__',
     '__getitem__',
     '__getnewargs__',
     '__gt__',
     '__hash__',
     '__init__',
     '__init_subclass__',
     '__iter__',
     '__le__',
     '__len__',
     '__lt__',
     '__mod__',
     '__mul__',
     '__ne__',
     '__new__',
     '__reduce__',
     '__reduce_ex__',
     '__repr__',
     '__rmod__',
     '__rmul__',
     '__setattr__',
     '__sizeof__',
     '__str__',
     '__subclasshook__',
     'capitalize',
     'casefold',
     'center',
     'count',
     'encode',
     'endswith',
     'expandtabs',
     'find',
     'format',
     'format_map',
     'index',
     'isalnum',
     'isalpha',
     'isdecimal',
     'isdigit',
     'isidentifier',
     'islower',
     'isnumeric',
     'isprintable',
     'isspace',
     'istitle',
     'isupper',
     'join',
     'ljust',
     'lower',
     'lstrip',
     'maketrans',
     'partition',
     'replace',
     'rfind',
     'rindex',
     'rjust',
     'rpartition',
     'rsplit',
     'rstrip',
     'split',
     'splitlines',
     'startswith',
     'strip',
     'swapcase',
     'title',
     'translate',
     'upper',
     'zfill']
    

    可以发现字符串对象有很多方法可以使用,我们这里只关心以小写字母开头的方法


    1、capitalize
    我们先看一下该方法的用法说明

    利用help函数来查看该方法的使用说明
    >>> help(name.capitalize)
      Help on built-in function capitalize:
    
    capitalize(...) method of builtins.str instance
        S.capitalize() -> str
        
        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
    

    可以知道该方法的作用是使字符串的第一个字符变成大写字母如果字符串的第一个字符已经是大写字母或者是非英文字符,就不会有变化

    如:

    >>> name.capitalize()
        'Xiaoniao'
    >>> '598*'.capitalize()
        '598*'
    >>> '中国'.capitalize()
        '中国'

    相关文章

      网友评论

          本文标题:Python中关于字符串的操作

          本文链接:https://www.haomeiwen.com/subject/pqxukqtx.html