字符串是Python中最常见的类型,通过在引号之间包含字符的方式来创建。

字符串类型是不可变的。

一、字符串的创建

创建与赋值

>>> FirstString = 'Hello World!'
>>> print(FirstString)
Hello World!

访问字符串的值

>>> FirstString[0]
'H'

改变一个字符串

>>> FirstString = FirstString[:6] + 'Python'
>>> FirstString
'Hello Python'

二、字符串操作

a.标准类型操作符

>>> str1 = 'abc'
>>> str2 = 'opq'
>>> str3 = 'xyz'
>>> str1 < str2
True
>>> str2 != str3
True
>>> str1 < str3 and str2 == 'xyz'
False

b.序列操作符

索引

  • 正向索引
  • 反向索引

    0   1   2   3

    a   b   c   d

   -4  -3 -2  -1

切片

使用一个数值范围(:)作为切片操作的参数可以返回一串连续的字符。

[start:end],我们可以访问到包括start在内到end(不包括end)的所有字符,即start<=x<end。

>>> FirstString[0:5]
'Hello'

三、格式化操作符(%)

通过使用%来实现操作符的格式化。

>>> 'My computer name is: %s' % 'Jef'
'My computer name is: Jef'

四、内建函数

python string 处理 python里面string_String

python string 处理 python里面string_字符串_02

def capitalize(self): 
   #S.capitalize() -> str
   #把字符串的第一个字符大写

   def casefold(self): 
   #S.casefold() -> str
   #将字符串中所有大学字母改为小写
   >>> name = 'AbCd'
   >>> name.casefold()
   'abcd'

   def center(self, width, fillchar=None): 
   #将一个字符串居中,并使用填充空格至长度width的新字符串
   >>> name = 'Jef'
   >>> name.center(20,'*')
   '********Jef*********'

   def count(self, sub, start=None, end=None):
   #返回str在string里面出现的次数,可指定start与end的位置     
   >>> name = 'Jeffrey' 
   >>> name.count('ef',0,6) 
   1

   def encode(self, encoding='utf-8', errors='strict'): 
   #encoding指定的编码格式解码string 
   >>>name.encode(‘gbk’) 

   def endswith(self, suffix, start=None, end=None):
   #检查是否以某个字符结束,可指定start与end范围 

   def expandtabs(self, tabsize=8):
   #把tabs转换为空格,默认一个tab转换为8个空格
        """ 
   def find:
   #检测sub是否在字符串中
   >>> name = 'Jeffrey'
   >>> name.find('ef',0,5)
   1

    def format(*args, **kwargs): 
    #字符串格式化
    >>> name = 'Python is {0}'
    >>> name = name.format('No.1')
    >>> print(name)
    Python is No.1

    def format_map(self, mapping): 
        S.format_map(mapping) -> str 
      
    def index(self, sub, start=None, end=None): 
    #与find方法一直,区别在于index会返回一个异常
        """ 
    def isalnum(self): 
    #判断字符串中至少有一个字符并且所有字符都是字母或数字则返
       回True,否则返回False

    def isalpha(self): 
    #判断字符串中至少有一个字符并且所有字符都是字母则返回True,
       否则返回False

    def isdecimal(self):
    #判断字符串只包含十进制数字则返回True 否则返回False

    def isdigit(self): 
    #判断字符串中只包含数字则返回True 否则返回False

    def isidentifier(self): 
    #判断字符串是否是合法的标识符

    def islower(self): 
    #判断字符串中都是小写字母

    def isnumeric(self): 
    #判断字符串中只包含数字字符,则返回True,否则返回False

    def isprintable(self): # real signature unknown; restored from __doc__ 
        """ 
        S.isprintable() -> bool 
        
        Return True if all characters in S are considered 
        printable in repr() or S is empty, False otherwise. 
       """ 
        return False 

    def isspace(self): #
    #判断字符串中是否只包含空格

    def istitle(self):
    #判断字符串是标题化的(见title())则返回True,否则返回False

    def isupper(self): 
    #判断字符串中都是大写字母
        
    def join(self, iterable): 
    #合并一个新的字符串
    >>> li = ['J','e','f']
    >>> result = "".join(li)
    >>> print(result)
    Jef

    def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ 
    #返回一个原字符串左对齐,并使用空格填充至长度width 的新字符串

    def lower(self): 
    #转换字符串中所有大写字符为小写

    def lstrip(self, chars=None): 
    #截掉string 左边的空格

    def maketrans(self, *args, **kwargs): # real signature unknown 
       
    def partition(self, sep):
    #将字符串进行分割
    >>> name = 'jefissmart'
    >>> result = name.partition('is')
    >>> print(result)
    ('jef', 'is', 'smart')

    def replace(self, old, new, count=None): 
    #将字符串中的old 替换成new,可指定次数   

    def rfind(self, sub, start=None, end=None): 
    #类似于find()函数,不过是从右边开始查找

    def rindex(self, sub, start=None, end=None): 
    #类似于index(),不过是从右边开始

    def rjust(self, width, fillchar=None): 
    #返回一个原字符串右对齐,并使用空格填充至长度width 的新字符串

    def rpartition(self, sep): 
    #

    def rsplit(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ 
        """ 
        S.rsplit(sep=None, maxsplit=-1) -> list of strings 
        
        Return a list of the words in S, using sep as the 
        delimiter string, starting at the end of the string and 
        working to the front.  If maxsplit is given, at most maxsplit 
        splits are done. If sep is not specified, any whitespace string 
        is a separator. 
       """ 
        return [] 

   def rstrip(self, chars=None): # real signature unknown; restored from __doc__ 
        """ 
        S.rstrip([chars]) -> str 
        
        Return a copy of the string S with trailing whitespace removed. 
        If chars is given and not None, remove characters in chars instead. 
       """ 
        return "" 

    def split(self, sep=None, maxsplit=-1): 
    #返回一个以sep分隔的列表,maxsplit指定拆分次数

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

    def startswith(self, prefix, start=None, end=None): 
    #检查字符串是否是以某个obj 开头

    def strip(self, chars=None): 
    #在字符串上执行lstrip()和rstrip()

    def swapcase(self): 
    #翻转string 中的大小写
    def title(self): 
    #返回"标题化"的string,就是说所有单词都是以大写开始,其余字母均为      小写

    def translate(self, table): 
    #根据str 给出的表(包含256 个字符)转换string 的字符

    def upper(self): 
    #转换string 中的小写字母为大写
    >>> name = 'Jef Is Smart'
    >>> result = name.upper()
    >>> print(result)
    JEF IS SMART

    def zfill(self, width):
    #返回长度为width 的字符串,原字符串string 右对齐,前面填充0

    def __add__(self, *args, **kwargs): # real signature unknown 
        """ Return self+value.""" 
        pass 

    def __contains__(self, *args, **kwargs): # real signature unknown 
        """ Return key in self.""" 
        pass 

    def __eq__(self, *args, **kwargs): # real signature unknown 
        """ Return self==value.""" 
        pass 

    def __format__(self, format_spec): # real signature unknown; restored from __doc__ 
        """ 
        S.__format__(format_spec) -> str 
        
        Return a formatted version of S as described by format_spec. 
       """ 
        return "" 

    def __getattribute__(self, *args, **kwargs): # real signature unknown 
        """ Return getattr(self, name).""" 
        pass 

    def __getitem__(self, *args, **kwargs): # real signature unknown 
        """ Return self[key].""" 
        pass 

    def __getnewargs__(self, *args, **kwargs): # real signature unknown 
        pass 

    def __ge__(self, *args, **kwargs): # real signature unknown 
        """ Return self>=value.""" 
        pass 

    def __gt__(self, *args, **kwargs): # real signature unknown 
        """ Return self>value.""" 
        pass 

    def __hash__(self, *args, **kwargs): # real signature unknown 
        """ Return hash(self).""" 
        pass 

    def __init__(self, value='', encoding=None, errors='strict'): # known special case of str.__init__ 
        """ 
        str(object='') -> str 
        str(bytes_or_buffer[, encoding[, errors]]) -> str 
        
        Create a new string object from the given object. If encoding or 
        errors is specified, then the object must expose a data buffer 
        that will be decoded using the given encoding and error handler. 
        Otherwise, returns the result of object.__str__() (if defined) 
        or repr(object). 
        encoding defaults to sys.getdefaultencoding(). 
        errors defaults to 'strict'. 
        # (copied from class doc) 
       """ 
        pass 

    def __iter__(self, *args, **kwargs): # real signature unknown 
        """ Implement iter(self).""" 
        pass 

    def __len__(self, *args, **kwargs): # real signature unknown 
        """ Return len(self).""" 
        pass 

    def __le__(self, *args, **kwargs): # real signature unknown 
        """ Return self<=value.""" 
        pass 

    def __lt__(self, *args, **kwargs): # real signature unknown 
        """ Return self<value.""" 
        pass 

    def __mod__(self, *args, **kwargs): # real signature unknown 
        """ Return self%value.""" 
        pass 

    def __mul__(self, *args, **kwargs): # real signature unknown 
        """ Return self*value.n""" 
        pass 

    @staticmethod# known case of __new__ 
    def __new__(*args, **kwargs): # real signature unknown 
        """ Create and return a new object.  See help(type) for accurate signature.""" 
        pass 

    def __ne__(self, *args, **kwargs): # real signature unknown 
        """ Return self!=value.""" 
        pass 

    def __repr__(self, *args, **kwargs): # real signature unknown 
        """ Return repr(self).""" 
        pass 

    def __rmod__(self, *args, **kwargs): # real signature unknown 
        """ Return value%self.""" 
        pass 

    def __rmul__(self, *args, **kwargs): # real signature unknown 
        """ Return self*value.""" 
        pass 

    def __sizeof__(self): # real signature unknown; restored from __doc__ 
        """ S.__sizeof__() -> size of S in memory, in bytes""" 
        pass 

    def __str__(self, *args, **kwargs): # real signature unknown 
        """ Return str(self).""" 
        pass 


class super(object): 
   """ 
    super() -> same as super(__class__, <first argument>) 
    super(type) -> unbound super object 
    super(type, obj) -> bound super object; requires isinstance(obj, type) 
    super(type, type2) -> bound super object; requires issubclass(type2, type) 
    Typical use to call a cooperative superclass method: 
    class C(B): 
        def meth(self, arg): 
            super().meth(arg) 
    This works for class methods too: 
    class C(B): 
        @classmethod 
        def cmeth(cls, arg): 
            super().cmeth(arg) 
   """ 
    def __getattribute__(self, *args, **kwargs): # real signature unknown 
        """ Return getattr(self, name).""" 
        pass 

    def __get__(self, *args, **kwargs): # real signature unknown 
        """ Return an attribute of instance, which is of type owner.""" 
        pass 

    def __init__(self, type1=None, type2=None): # known special case of super.__init__ 
        """ 
        super() -> same as super(__class__, <first argument>) 
        super(type) -> unbound super object 
        super(type, obj) -> bound super object; requires isinstance(obj, type) 
        super(type, type2) -> bound super object; requires issubclass(type2, type) 
        Typical use to call a cooperative superclass method: 
        class C(B): 
            def meth(self, arg): 
                super().meth(arg) 
        This works for class methods too: 
        class C(B): 
            @classmethod 
            def cmeth(cls, arg): 
                super().cmeth(arg) 
        
        # (copied from class doc) 
       """ 
        pass 

    @staticmethod# known case of __new__ 
    def __new__(*args, **kwargs): # real signature unknown 
        """ Create and return a new object.  See help(type) for accurate signature.""" 
        pass 

    def __repr__(self, *args, **kwargs): # real signature unknown 
        """ Return repr(self).""" 
        pass 

    __self_class__ = property(lambda self: type(object)) 
   """the type of the instance invoking super(); may be None 

    :type: type 
   """ 

    __self__ = property(lambda self: type(object)) 
   """the instance invoking super(); may be None 

    :type: type 
   """ 

    __thisclass__ = property(lambda self: type(object)) 
   """the class invoking super() 

    :type: type 
   """

method