设为首页 加入收藏

TOP

基本数据str的操作
2018-12-13 18:28:25 】 浏览:37
Tags:基本 数据 str 操作
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lzz6660888/article/details/54803672

Python版本:Python 3.5.3rc1


知识碎片:

1. Python中的切片操作

使用index作为分割界线,分割的结果为大于等于前index,小于等于后index。

e.g.:

>>> S = "abcdefg"
>>> #abcdefg
>>> #0123456
>>> S[0:3:7]
'a'  #??????????
>>> S[0:3]
'abc'
>>> S[3:6]
'def'
>>> S[3:7]
'defg'
>>> S[3:8] #越界
'defg' #不影响结果

2.Python中的格式化输出

占位符:占位符最基本的为形式为{}
  填写模型为:  
{【key】【:】【填充字符】【对齐方式】【输出格式】【输出长度】}
P.s.:填充字符默认为空格、输出长度若小于等于填充内容长度则不填充。
  1. key格式:

    1、空:
         此时默认为从0开始递增填充的数字填充。进行format操作时,填充参数必须与占位符个数相同。
    2、数字填充:
        1>数字填充必须从0开始,但是顺序可以打乱并且同一数字可以多次出现。
        2>进行format操作时,填充参数按照‘0,1,2……’的顺序填充,参数的个数应大于等于占位符中出现的数字(类型)个数,溢出的部分将被舍去。
        3>不可以用key操作。如S.format(0='abc')是不可以的。
    3、key填充:
        1>占位符中使用的为符合命名标准的变量名。
        2>进行format操作时,必须一一对应的填充所有占位符,但是顺序可以改变。
    4、key数字混合:
    进行format操作时,必须先写数字占位的参数,再写key占位的参数。
    
  2. 对齐格式:

        '<' (默认)左对齐
        '>' 右对齐
        '^' 中间对齐
        '=' (只用于数字)在小数点后进行补齐
    
  3. 输出格式:

        'b' - 二进制。将数字以2为基数进行输出。
        'c' - 字符。在打印之前将整数转换成对应的Unicode字符串。
        'd' - 十进制整数。将数字以10为基数进行输出。
        'f' - 十进制浮点数。将数字以10.0为基数的小数进行输出。
        'o' - 八进制。将数字以8为基数进行输出。
        'x' - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
        'e' - 幂符号。用科学计数法打印数字。用'e'表示幂。
        'g' - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
        'n' - 数字。当值为整数时和'd'相同,值为浮点数时和'g'相同。不同的是它会根据区域设置插入数字分隔符。
        '%' - 百分数。将数值乘以100然后以fixed-point('f')格式打印,值后面会有一个百分号。
    

Methods defined here:

def capitalize(self): 
    # real signature unknown; restored from __doc__
    # 将S的开头若是字母则大写,其余字母转为小写并将其返回。
    # 例如 "anjf efRFSDF"  ->'Anjf efrfsdf'
        """
        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 casefold(self): 
    # real signature unknown; restored from __doc__
    # 将S中全部英文改为小写并返回
    # 特点:对Unicode适用
        """
        S.casefold() -> str

        Return a version of S suitable for caseless comparisons.
        """
        return ""   
def lower(self): 
    # real signature unknown; restored from __doc__
    # 将S中全部英文改为小写并返回
    # 特点:只对ASCII码适用
        """
        S.lower() -> str

        Return a copy of the string S converted to lowercase.
        """
        return ""
def upper(self): 
    # real signature unknown; restored from __doc__
    # 将S中全部英文改为大写并返回
    # 特点:只对ASCII码适用
        """
        S.upper() -> str

        Return a copy of S converted to uppercase.
        """
        return ""
def swapcase(self): 
    # real signature unknown; restored from __doc__
    # 将S中全部英文改为大写并返回
    # 特点:对Unicode适用
        """
        S.swapcase() -> str

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

lower()、upper()与casefolk()、swapcase()的区别 :

 casefolk()swapcase()适用于Unicode,而lower()upper()只适用于ASCII码,所以在使用过程中在只出现中文和英文的情况下,可以使用lower()upper();出现其他国家语言时,需要使用casefolk()swapcase()

def center(self, width, fillchar=None):
     # real signature unknown; restored from __doc__
     # 将字符串居中填充并返回,width为填充后的长度,fillchar为填充时使用的字符(默认为空格)。
     # 若width小于等于S的长度,则不会填充。
     # fillchar只能为一个字符。
        """
        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 ""
def ljust(self, width, fillchar=None): 
    # real signature unknown; restored from __doc__
    # 使用字符fillchar填充,左对齐填充S至width长度,若S长度大于等于width则返回S。
        """
        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 ""
def rjust(self, width, fillchar=None): 
    # real signature unknown; restored from __doc__
    # 使用字符fillchar填充,右对齐填充S至width长度,若S长度大于等于width则返回S。
        """
        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 ""

def count(self, sub, start=None, end=None):
     # real signature unknown; restored from __doc__
     # 统计字符串S[start:end]中 sub出现的次数,并将其返回。
        """
        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 encode(self, encoding='utf-8', errors='strict'): 
     # real signature unknown; restored from __doc__
     # 将字符串按照encoding(默认为utf-8)的编码规则编码
     # 对应 byte 类型的 decode() 操作

        """
        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""

e.g.:

>>> K = "哈哈哈"
>>> K_uft = K.encode("utf-8")
>>> K_gbk = K.encode("gbk")
>>> K_uft
b'\xe5\x93\x88\xe5\x93\x88\xe5\x93\x88'
>>> K_gbk
b'\xb9\xfe\xb9\xfe\xb9\xfe'
>>> K_uft.decode()
'哈哈哈'

def endswith(self, suffix, start=None, end=None): 
    # real signature unknown; restored from __doc__ 
    # 检查S[start:end]是否以字符串suffix结尾。并返回其真假值。
        """
        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
def startswith(self, prefix, start=None, end=None): 
    # real signature unknown; restored from __doc__
    # 检查S[start:end]是否以字符串prefix开头。并返回其真假值。
        """
        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

def expandtabs(self, tabsize=8): 
    # real signature unknown; restored from __doc__
    # 使用tabsize个(默认为8个)空格替换S中的制表符,并将其返回。
        """
        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 find(self, sub, start=None, end=None): 
    # real signature unknown; restored from __doc__
    # 返回S[start:end]中sub第一次出现的index,若没有找到则返回-1
    # sub可以是一个字符,也可以是一个字符串
        """
        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
def rfind(self, sub, start=None, end=None): 
    # real signature unknown; restored from __doc__
    # 返回S[start:end]中sub最后一次(从右侧找起)出现的index,若没有找到则返回-1
    # sub可以是一个字符,也可以是一个字符串
        """
        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
def index(self, sub, start=None, end=None): 
    # real signature unknown; restored from __doc__
    # 返回S[start:end]中sub第一次出现的index,若没有找到则报错
    # sub可以是一个字符,也可以是一个字符串
        """
        S.index(sub[, start[, end]]) -> int

        Like S.find() but raise ValueError when the substring is not found.
        """
        return 0
def rindex(self, sub, start=None, end=None): 
    # real signature unknown; restored from __doc__
    # 返回S[start:end]中sub最后一次出现(从右侧找起)的index,若没有找到则报错。
    # sub可以是一个字符,也可以是一个字符串
        """
        S.rindex(sub[, start[, end]]) -> int

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

def format(self, *args, **kwargs): 
    # known special case of str.format
    # 将S根据参数格式化填充并返回。

        """
        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
def format_map(self, mapping):
     # real signature unknown; restored from __doc__
     # 使用字典格式化填充对应key,如果字典中没有匹配的关键字,则报错。
     # 本方法只能使用在只使用key占位符的字符串中。
        """
        S.format_map(mapping) -> str

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

def isalnum(self): 
    # real signature unknown; restored from __doc__
    # 如果字符串中全部的字符都是字母或者数字则返回TRUE,否则返回FALSE
    # P.s.:空格不属于字母或数字
        """
        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__
    # 如果字符串中全部的字符都是字母则返回TRUE,否则返回FALSE
        """
        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__
    # 如果字符串中全部的字符都是数字则返回TRUE,否则返回FALSE
    # True: Unicode数字,,全角数字(双字节)
    # False: 罗马数字,汉字数字
    # Error: byte数字(单字节)
        """
        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__
    # 如果字符串中全部的字符都是数字则返回TRUE,否则返回FALSE
    # True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字
    # False: 汉字数字
    # Error: 无
        """
        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 isnumeric(self): 
    # real signature unknown; restored from __doc__
    # 如果字符串中全部的字符都是数字则返回TRUE,否则返回FALSE
    # True: Unicode数字,全角数字(双字节),罗马数字,汉字数字
    # False: 无
    # Error: byte数字(单字节)
        """
        S.isnumeric() -> bool

        Return True if there are only numeric characters in S,
        False otherwise.
        """
        return False
def islower(self): 
    # real signature unknown; restored from __doc__
    # 如果字符串中的所有英文都是小写则返回TRUE,否则返回FALSE
        """
        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 isupper(self): 
    # real signature unknown; restored from __doc__
    # 如果字符串中的所有英文都是大写则返回TRUE,否则返回FALSE
        """
        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
def isspace(self): 
    # real signature unknown; restored from __doc__
    # 如果S中只包含空格/制表符/ \n ...(空白)则返回TRUE,否则返回FALSE。
        """
        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是否符合英文标题格式(所有单词只有开头字母大写),如果正确则返回TRUE,否则返回FALSE。
        """
        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 title(self): 
    # real signature unknown; restored from __doc__
    # 将S转化为title格式,并返回。
        """
        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 isidentifier(self): 
    # real signature unknown; restored from __doc__
    # 判断字符串S是不是一个合法的标识符,如果是则返回TRUE,否则返回FALSE
        """
        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
defisprintable(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 join(self, iterable): 
    # real signature unknown; restored from __doc__
    # 在一个可迭代的数据(iterable)的每个元素中,插入字符串S并返回。
    # iterable: 字符串, 元组, 列表, 字典(只在KEY中穿插)。
    """
    e.g.:
        list = ['P','y','t','h','o','n']
        S = "***"
        S.join(list)
        'P***y***t***h***o***n'
    """
        """
        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 strip(self, chars=None): 
    # real signature unknown; restored from __doc__
    # 删除S中两侧的chars(默认为None),并返回。
        """
        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 ""
def lstrip(self, chars=None): 
    # real signature unknown; restored from __doc__
    # 删除S中左侧的chars(默认为None),并返回。
        """
        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 ""
def rstrip(self, chars=None): 
    # real signature unknown; restored from __doc__
    # 删除S中右侧的chars(默认为None),并返回。
        """
        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 partition(self, sep): 
    # real signature unknown; restored from __doc__
    # 从字符串左侧起找到sep,将其划分为3个部分,并用元组返回。
    # 若找到则返回(head, sep, tail)
    # 找不到则返回(S,'','')
        """
        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 rpartition(self, sep): 
    # real signature unknown; restored from __doc__
    # 从字符串右侧起找到sep,将其划分为3个部分,并用元组返回。
    # 若找到则返回(head, sep, tail)
    # 找不到则返回('','',S)
        """
        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

def zfill(self, width):
    # real signature unknown; restored from __doc__
    # 将从左侧用零填充至长度为width(原字符串右对齐,前面填充0 )。
        """
        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 ""

def split(self, sep=None, maxsplit=-1): 
    # real signature unknown; restored from __doc__
    # 将S按sep由左侧开始划分maxsplit次(默认为-1时,为最大划分),若没有则返回[sep]。
    # 每次划分后,分为左侧与右侧,当sep处于边界时则分为一部分和''。
        """
        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 rsplit(self, sep=None, maxsplit=-1): 
    # real signature unknown; restored from __doc__
    # 将S按sep从右侧开始划分maxsplit次(默认为-1时,为最大划分),若没有则返回[sep]。
    # 每次划分后,分为左侧与右侧,当sep处于边界时则分为一部分和''。
        """
        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 splitlines(self, keepends=None): 
    # real signature unknown; restored from __doc__
    # 按照行('\r', '\n','\r\n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
    #P.s.:\r\n分隔1次
        """
        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 []

def replace(self, old, new, count=None): 
    # real signature unknown; restored from __doc__
    # 将S中的 old,替换成 new,最多替换count个(默认为全部替换)。
        """
        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 ""

字符串中的翻译操作(暂略):

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
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 ""
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python学习笔记 --- Python命名规.. 下一篇Python学习笔记 --- Python 编码..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目