python基础数据类型之字符串string

一、定义 

定义:它是一个有序的字符的集合,用于存储和表示基本的文本信息,称之为字符串

   字符串的结构类型为'...'  "..."  "'..."'

   字符串一旦创建,则不可以修改

   一旦修改或者拼接,都会造成重新生成字符串,则要赋予一个新的值

二、字符串的使用

  abc = 'adffadsf'

  a = "哈喽"

三、字符串的处理

  • 移除空白
    1 str1 = 'abcdefg@@@'
    2 str2 = '哈哈哈哈嘿嘿'
    3 print(str1.strip('@')) #会去掉两边的指定字符,默认为空白字符
  • 分割
    str1 = 'abc@defg@打发第三方'
    str2 = '哈哈哈哈嘿嘿'
    
    print(str1.split('@')) #会去掉两边的指定字符,默认为空白字符生成一个列表['abc', 'defg', '打发第三方']
  • 长度
    1 str1 = 'abc@defg@打发第三方'
    2 str2 = '哈哈哈哈嘿嘿'
    3 
    4 print(len(str1)) # 显示字符串的长度14
  • 索引
    1 str1 = 'abc@defg@打发第三方'
    2 str2 = '哈哈哈哈嘿嘿'
    3 
    4 print(str1.index('')) # 找到'打'字的位置9
  • 切片
    1 str1 = 'abc@defg@打发第三方'
    2 str2 = '哈哈哈哈嘿嘿'
    3 
    4 print(str1[0:2]) # 支持切片,哈哈

     

四、字符串常用的方法:

  大小写转换:lower(),upper(),capitalize()

  判断开头,或者结尾:startwith('a'),endwith('b')

  判断是否为数字,字母啥的:isalnum(),isalpha(),isdigit()

  islower(),isspace().......

五、str的官方文档

class str(object):
    """
    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'.
    """

    #----------------------------------------------------- 查找-----------------------------------------
    # 从右边查找子序列在字符串第一次出现的位置,找不到返回-1
    def rfind(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.rfind(sub[, start[, end]]) -> int

        Return the highest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

    # 查找子序列在字符串第一次出现的位置,找不到返回-1
    def find(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.find(sub[, start[, end]]) -> int

        Return the lowest index in S where substring sub is found,
        such that sub is contained within S[start:end].  Optional
        arguments start and end are interpreted as in slice notation.

        Return -1 on failure.
        """
        return 0

    # 从右边查找子序列在字符串第一次出现的位置,会抛出异常ValueError: substring not found
    def rindex(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.rindex(sub[, start[, end]]) -> int

        Like S.rfind() but raise ValueError when the substring is not found.
        """
        return 0

    def index(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.index(sub[, start[, end]]) -> int

        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0

    # 是否以prefix
    def startswith(self, prefix, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.startswith(prefix[, start[, end]]) -> bool

        Return True if S starts with the specified prefix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        prefix can also be a tuple of strings to try.
        """
        return False

    # 是否以suffix结束
    def endswith(self, suffix, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.endswith(suffix[, start[, end]]) -> bool

        Return True if S ends with the specified suffix, False otherwise.
        With optional start, test S beginning at that position.
        With optional end, stop comparing S at that position.
        suffix can also be a tuple of strings to try.
        """
        return False

    # 在指定的范围内查找sub的个数
    def count(self, sub, start=None, end=None):  # real signature unknown; restored from __doc__
        """
        S.count(sub[, start[, end]]) -> int

        Return the number of non-overlapping occurrences of substring sub in
        string S[start:end].  Optional arguments start and end are
        interpreted as in slice notation.
        """
        return 0

    #----------------------------------------------------- 大小写转化-----------------------------------------
    # 首字母大写
    def capitalize(self):  # real signature unknown; restored from __doc__
        """
        S.capitalize() -> str 首字母大写

        Return a capitalized version of S, i.e. make the first character
        have upper case and the rest lower case.
        """
        return ""

    # 大小写转化
    def swapcase(self):  # real signature unknown; restored from __doc__
        """
        S.swapcase() -> str

        Return a copy of S with uppercase characters converted to lowercase
        and vice versa.
        """
        return ""

    # 所有的单词首字母都大写
    def title(self):  # real signature unknown; restored from __doc__
        """
        S.title() -> str

        Return a titlecased version of S, i.e. words start with title case
        characters, all remaining cased characters have lower case.
        """
        return ""
    # 大写

    def upper(self):  # real signature unknown; restored from __doc__
        """
        S.upper() -> str

        Return a copy of S converted to uppercase.
        """
        return ""
    # 小写
    def lower(self):  # real signature unknown; restored from __doc__
        """
        S.lower() -> str

        Return a copy of the string S converted to lowercase.
        """
        return ""
    # 字符串转换成小写,用于不区分大小写的字符串比较
    def casefold(self):  # real signature unknown; restored from __doc__
        """
        S.casefold() -> str

        Return a version of S suitable for caseless comparisons.
        """
        return ""

    ##----------------------------------------------------- 显示-----------------------------------------
    # 内容居中,width 宽度 ,fillchar 空白用啥填充
    def center(self, width, fillchar=None):  # real signature unknown; restored from __doc__
        """
        S.center(width[, fillchar]) -> str

        Return S centered in a string of length width. Padding is
        done using the specified fill character (default is a space)
        """
        return ""

    # 在字符串的左边填充0,不会截断字符串
    def zfill(self, width):  # real signature unknown; restored from __doc__
        """
        S.zfill(width) -> str

        Pad a numeric string S with zeros on the left, to fill a field
        of the specified width. The string S is never truncated.
        """
        return ""

    # 内容左对齐,右边用fillchar填充
    def ljust(self, width, fillchar=None):  # real signature unknown; restored from __doc__
        """
        S.ljust(width[, fillchar]) -> str

        Return S left-justified in a Unicode string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""
    # 内容右对齐,右边用fillchar填充
    def rjust(self, width, fillchar=None):  # real signature unknown; restored from __doc__
        """
        S.rjust(width[, fillchar]) -> str

        Return S right-justified in a string of length width. Padding is
        done using the specified fill character (default is a space).
        """
        return ""

    # ---------------------------------------------------截断-----------------------------------------

    # 把左边的chars截断
    def lstrip(self, chars=None):  # real signature unknown; restored from __doc__
        """
        S.lstrip([chars]) -> str

        Return a copy of the string S with leading whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""
    # 把右边的chars截断
    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 ""
    # 把左右的chars都截掉
    def strip(self, chars=None):  # real signature unknown; restored from __doc__
        """
        S.strip([chars]) -> str

        Return a copy of the string S with leading and trailing
        whitespace removed.
        If chars is given and not None, remove characters in chars instead.
        """
        return ""

        # ---------------------------------------------------拆分-----------------------------------------
    # 从右边找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 split(self, sep=None, maxsplit=-1):  # real signature unknown; restored from __doc__
        """
        S.split(sep=None, maxsplit=-1) -> list of strings

        Return a list of the words in S, using sep as the
        delimiter string.  If maxsplit is given, at most maxsplit
        splits are done. If sep is not specified or is None, any
        whitespace string is a separator and empty strings are
        removed from the result.
        """
        return []

    # 根据换行符进行切割
    def splitlines(self, keepends=None):  # real signature unknown; restored from __doc__
        """
        S.splitlines([keepends]) -> list of strings

        Return a list of the lines in S, breaking at line boundaries.
        Line breaks are not included in the resulting list unless keepends
        is given and true.
        """
        return []

    # 右找sep,拆成三部分 ,左,右,sep
    def rpartition(self, sep):  # real signature unknown; restored from __doc__
        """
        S.rpartition(sep) -> (head, sep, tail)

        Search for the separator sep in S, starting at the end of S, and return
        the part before it, the separator itself, and the part after it.  If the
        separator is not found, return two empty strings and S.
        """
        pass
    # 左边找sep,拆成三部分 ,左,右,sep
    def partition(self, sep):  # real signature unknown; restored from __doc__
        """
        S.partition(sep) -> (head, sep, tail)

        Search for the separator sep in S, and return the part before it,
        the separator itself, and the part after it.  If the separator is not
        found, return S and two empty strings.
        """
        pass

        # ---------------------------------------------------格式化-----------------------------------------
    # 执行字符串格式化操作,替换字段使用{}分隔,替换字段可以是表
    def format(self, *args, **kwargs):  # known special case of str.format
        """
        S.format(*args, **kwargs) -> str

        Return a formatted version of S, using substitutions from args and kwargs.
        The substitutions are identified by braces ('{' and '}').
        """
        pass

    # 执行字符串格式化操作,替换字段使用{}分隔,同str.format
    def format_map(self, mapping):  # real signature unknown; restored from __doc__
        """
        S.format_map(mapping) -> str

        Return a formatted version of S, using substitutions from mapping.
        The substitutions are identified by braces ('{' and '}').
        """
        return ""

    # ---------------------------------------------------编码-----------------------------------------

    def encode(self, encoding='utf-8', errors='strict'):  # real signature unknown; restored from __doc__
        """
        S.encode(encoding='utf-8', errors='strict') -> bytes

        Encode S using the codec registered for encoding. Default encoding
        is 'utf-8'. errors may be given to set a different error
        handling scheme. Default is 'strict' meaning that encoding errors raise
        a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and
        'xmlcharrefreplace' as well as any other name registered with
        codecs.register_error that can handle UnicodeEncodeErrors.
        """
        return b""

    # ---------------------------------------------------字符串拼接-----------------------------------------
    # 利用self 将iterable拼接起来
    def join(self, iterable):  # real signature unknown; restored from __doc__
        """
        S.join(iterable) -> str

        Return a string which is the concatenation of the strings in the
        iterable.  The separator between elements is S.
        """
        return ""


    # ---------------------------------------------------字符串替换-----------------------------------------
    def replace(self, old, new, count=None):  # real signature unknown; restored from __doc__
        """
        S.replace(old, new[, count]) -> str

        Return a copy of S with all occurrences of substring
        old replaced by new.  If the optional argument count is
        given, only the first count occurrences are replaced.
        """
        return ""

    # 用空格替换tab键
    def expandtabs(self, tabsize=8):  # real signature unknown; restored from __doc__
        """
        S.expandtabs(tabsize=8) -> str

        Return a copy of S where all tab characters are expanded using spaces.
        If tabsize is not given, a tab size of 8 characters is assumed.
        """
        return ""

    # 返回一个转换表
    def maketrans(self, *args, **kwargs):  # real signature unknown
        """
        Return a translation table usable for str.translate().

        If there is only one argument, it must be a dictionary mapping Unicode
        ordinals (integers) or characters to Unicode ordinals, strings or None.
        Character keys will be then converted to ordinals.
        If there are two arguments, they must be strings of equal length, and
        in the resulting dictionary, each character in x will be mapped to the
        character at the same position in y. If there is a third argument, it
        must be a string, whose characters will be mapped to None in the result.
        """
        pass

    # 根据table表的映射关系,将字符串中的每个字符转换成另一个
    def translate(self, table):  # real signature unknown; restored from __doc__
        """
        S.translate(table) -> str

        Return a copy of the string S in which each character has been mapped
        through the given translation table. The table must implement
        lookup/indexing via __getitem__, for instance a dictionary or list,
        mapping Unicode ordinals to Unicode ordinals, strings, or None. If
        this operation raises LookupError, the character is left untouched.
        Characters mapped to None are deleted.
        """
        return ""



    # ---------------------------------------------------内容判断-----------------------------------------
    # alpha 字母 num数字 decimal小数 digit数字 identifier 有效标识符 numeric数字
    def isalnum(self):  # real signature unknown; restored from __doc__
        """
        S.isalnum() -> bool

        Return True if all characters in S are alphanumeric
        and there is at least one character in S, False otherwise.
        """
        return False

    def isalpha(self):  # real signature unknown; restored from __doc__
        """
        S.isalpha() -> bool

        Return True if all characters in S are alphabetic
        and there is at least one character in S, False otherwise.
        """
        return False

    def isdecimal(self):  # real signature unknown; restored from __doc__
        """
        S.isdecimal() -> bool

        Return True if there are only decimal characters in S,
        False otherwise.
        """
        return False

    def isdigit(self):  # real signature unknown; restored from __doc__
        """
        S.isdigit() -> bool

        Return True if all characters in S are digits
        and there is at least one character in S, False otherwise.
        """
        return False

    def isidentifier(self):  # real signature unknown; restored from __doc__
        """
        S.isidentifier() -> bool

        Return True if S is a valid identifier according
        to the language definition.

        Use keyword.iskeyword() to test for reserved identifiers
        such as "def" and "class".
        """
        return False

    def islower(self):  # real signature unknown; restored from __doc__
        """
        S.islower() -> bool

        Return True if all cased characters in S are lowercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

    def isnumeric(self):  # real signature unknown; restored from __doc__
        """
        S.isnumeric() -> bool

        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return 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):  # real signature unknown; restored from __doc__
        """
        S.isspace() -> bool

        Return True if all characters in S are whitespace
        and there is at least one character in S, False otherwise.
        """
        return False

    def istitle(self):  # real signature unknown; restored from __doc__
        """
        S.istitle() -> bool

        Return True if S is a titlecased string and there is at least one
        character in S, i.e. upper- and titlecase characters may only
        follow uncased characters and lowercase characters only cased ones.
        Return False otherwise.
        """
        return False

    def isupper(self):  # real signature unknown; restored from __doc__
        """
        S.isupper() -> bool

        Return True if all cased characters in S are uppercase and there is
        at least one cased character in S, False otherwise.
        """
        return False

 

  

posted @ 2017-04-11 18:28  skiler  阅读(191)  评论(0编辑  收藏  举报