zoukankan      html  css  js  c++  java
  • 序列(列表、元组、字符串)

      本节将会引入一个新的概念:数据结构。数据结构是通过某种方式(例如对元素进行编号)组织在一起的数据元素的集合,甚至可以是其他数据结构。在Python中,最基本都数据结构是序列(sequence)。序列中的每个元素被分配一个序号——即元素的位置,也称索引。第一个索引是0,第二个是1,以此类推。Python的内建序列主要为(列表、元组和字符串)

    本节目录

    1、列表

    2、元组

    3、字符串

    列表

      列表是我们最以后最常用的数据类型之一,通过列表可以对数据实现最方便的存储、修改等操作

    定义列表

    people=["name","age","hobby"]
    
    #定义一个空列表
    
    name=[]
    
    #定义一个长度为10的空列表
    
    >>> name1=[None]*10
    >>> print(name1)
    [None, None, None, None, None, None, None, None, None, None]
    View Code

    通过下标访问列表中的元素,下标从0开始计数

    >>> person=['name','age','hobby']
    >>> person[0]
    'name'
    >>> person[1]
    'age'
    >>> person[-1]
    'hobby'
    >>> person[-2]
    'age'
    View Code

    切片:取多个元素

    >>> person=['name','age','hobby','salary']
    >>> person[0:2]#取下标0至下标2之间的数字,包括0,不包括2
    ['name', 'age']  
    >>> person[:2] #如果是从头开始取,0可以忽略,跟上句效果一样
    ['name', 'age'] 
    >>> person[::2] ##后面的2是代表步长,每隔一个元素,就取一个
    ['name', 'hobby']
    View Code

    追加

    >>> singer=['zhangxueyou','liudehua']
    >>> singer.append('zhoujielun')
    >>> print(singer)
    ['zhangxueyou', 'liudehua', 'zhoujielun']
    View Code

    插入

    >>> singer
    ['zhangxueyou', 'liudehua', 'zhoujielun']
    >>> singer.insert(1,'插入到1位置')
    >>> print(singer)
    View Code

    修改

    >>> singer
    ['zhangxueyou', '插入到1位置', 'liudehua', 'zhoujielun']
    >>> singer[1]='我是修改后的'
    >>> singer
    ['zhangxueyou', '我是修改后的', 'liudehua', 'zhoujielun']
    View Code

    删除

    >>> del singer[1]
    >>> singer
    ['zhangxueyou', 'liudehua', 'zhoujielun']
    >>> singer.remove('liudehua') #删除指定元素
    >>> singer
    ['zhangxueyou', 'zhoujielun']
    >>> singer.pop() #删除最后一个元素
    'zhoujielun'
    >>> singer
    ['zhangxueyou']
    View Code

    注意:pop方法会移除列表中的一个元素(默认是最后一个),并且返回该元素的值,这是唯一一个既能修改列表又返回元素值(除了None)的列表方法。

    扩展:

    >>> singer
    ['zhangxueyou']
    >>> new_singer=['wangfeng','xuwei']
    >>> singer.extend(new_singer)
    >>> singer
    ['zhangxueyou', 'wangfeng', 'xuwei']
    >>> 
    View Code

    索引:返回下标

    >>> singer
    ['zhangxueyou', 'wangfeng', 'xuwei', 'zhangxueyou']
    >>> singer.index('wangfeng')
    1
    >>> singer.index('zhangxueyou')
    0  若列表中有多个,只返回找到的第一个的下标
    View Code

    统计

    >>> singer
    ['zhangxueyou', 'wangfeng', 'xuwei', 'zhangxueyou']
    >>> singer.count("zhangxueyou")
    2
    View Code

    浅copy与深copy:

    >>> animals=['pig',['dog','cat'],'monkey']
    >>> animals_copy=animals.copy() #浅copy
    >>> animals[2]='猴子'
    >>> animals[1][0]='小狗'
    >>> print(animals)
    ['pig', ['小狗', 'cat'], '猴子']
    >>> print(animals_copy)
    ['pig', ['小狗', 'cat'], 'monkey']    #我们只是把animals[1][0]的值修改了,为什么animals_copy[1][0]的值也跟着修改了
    #为什么出现上述这种情况呢?其实copy方法是浅copy,animals中嵌套的列表['dog','pig']实际上只是一个相当于指针的内存地址,['dog','pig']实际上是存放于独立于animals内存空间外的另一个内存空间,浅copy只是copy了['dog','pig']内存地址罢了
    
    #我们尝试引入copy模块来玩玩
    >>> import copy
    >>> animals=['pig',['dog','cat'],'monkey']
    >>> animals_copy1=copy.copy(animals)
    >>> animals_copy2=copy.deepcopy(animals)
    >>> animals[2]='猴子'
    >>> animals[1][0]='小狗'
    >>> print(animals)
    ['pig', ['小狗', 'cat'], '猴子']
    >>> print(animals_copy1)
    ['pig', ['小狗', 'cat'], 'monkey']  #同样是浅copy,与前面的方法效果一样
    >>> print(animals_copy2)
    ['pig', ['dog', 'cat'], 'monkey']    #深copy
    
    # 浅copy的三种方式
    person=['name',['dog','cat']]
    p1=copy.copy(person)
    p2=person[:]#完全切片
    p3=list(person)#工厂函数
    View Code

    成员资格:为了检查一个值是否在序列中,可以用in运算符。这个运算符检查某个条件是否为真:条件为真返回True,条件为假返回False。

    >>> numbers=[1,2,4,5,6,7]
    >>> 1 in numbers
    True
    >>> 8 in numbers
    False
    View Code

     sort方法:sort方法用于在原位置对列表进行排序。在“原位置排序”意味着改变原来的列表,从而让其中的元素能按一定的顺序排列,而不是简单地返回一个已排序的列表副本

    >>> x=[3,5,7,1,2,9]
    >>> x.sort()
    >>> x
    [1, 2, 3, 5, 7, 9]
    View Code

      当用户需要一个排好序的列表副本,同时又保留原有列表不变的时候,那么问题就来了,为了实现这个功能,我们自然而然就想到了如下的做法(实际上是错的):

    >>> x=[3,5,7,1,2,9]
    >>> y=x.sort() #Don't do this
    >>> print(y)
    None
    View Code

      因为sort()函数改变原来的列表,函数返回值是空值即None

      要实现这个功能的正确方法是,我们应该先把x的副本赋值给y,然后再对y进行排序:

    >>> x=[3,5,7,1,9,2]
    >>> y=x[:]
    >>> y.sort()
    >>> x
    [3, 5, 7, 1, 9, 2]
    >>> y
    [1, 2, 3, 5, 7, 9]
    View Code

      另一种获取已排序的列表副本的方法是,使用sorted函数

    >>> x=[3,5,7,1,9,2]
    >>> y=sorted(x)
    >>> y
    [1, 2, 3, 5, 7, 9]
    View Code

     sorted函数实质上可以用于任何序列((可用于任何可迭代对象)),却总是返回一个列表:

    >>> sorted("python")
    ['h', 'n', 'o', 'p', 't', 'y'] 

      注意:需分两次对列表调用sort方法以及reverse方法。如果打算通过x.sort().reverse()来实现,会发现是行不通的,因为x.sort()返回的是None。当然,sorted(x).reverse()是正确的做法。

    列表的高级排序

      sort方法有另外两个可选参数——key和reverse。如果要使用它们,那么就要通过名字指定(这叫关键字参数)。参数key和 cmp类似——必须提供一个在排序过程中使用的函数。然而,该函数并不是直接用来确定对象的大小,而是为每个元素创建一个键,然后所有元素根据键来排序。因此,如果根据元素的长度进行排序,那么可以使用len作为键函数:

    >>> x=['very','handsome','you','are']
    >>> x.sort(key=len)
    >>> x
    ['you', 'are', 'very', 'handsome']
    View Code

      另一个关键字参数reverse是简单的布尔值(True或者False)用来指明列表是否要进行反向排序。

    >>> x=[3,8,5,2,9]
    >>> x.sort(reverse=True)
    >>> x
    View Code

     

    元组

      元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表。一般来说,自己编写的程序中,几乎所有的情况下都可以用列表替代元组,不过可以使用元组作为字典的键,列表却不可以,因为键不可修改,所以不能用列表。

    创建一个元组

    singer=(“zhangxueyou”,“zhoujielun”)

      它只有2个方法,一个是count,一个是index

      如果要实现一个值得元组,在值得后面必须要加一个逗号:

    >>> x=(2,)
    >>> x
    (2,)
    View Code

    字符串

    字符串的创建

      在创建字符串时,既可以使用单引号(‘’),也可以使用双引号(“”)

      创建三重字符串,三重字符串可以跨越多行,输入时是什么样子,显示到屏幕上就是什么样子。

    >>>print("""
    Hiding from the rain and snow
    Trying to forget but I won't let go
    Looking at a crowded street
    Listening to my own heart beat
    """)
    Hiding from the rain and snow
    Trying to forget but I won't let go
    Looking at a crowded street
    Listening to my own heart beat
    View Code

    字符串的连接

      加号(+)运算符用于字符串的连接

    >>> print("Hi,"+"boy!")
    Hi,boy!

      使用换行( )可以将单条语句展开成多行。

    >>>print("Hiding from the rain and snow
    Trying to forget but I won't let go
    Looking at a crowded street
    Listening to my own heart beat")
    Hiding from the rain and snow
    Trying to forget but I won't let go
    Looking at a crowded street
    Listening to my own heart beat
    View Code

    字符串的重复

      使用重复运算符(*),可以实现字符串的重复打印

    例如:

    >>> print("Pie"*10)
    PiePiePiePiePiePiePiePiePiePie

    常用的字符串方法

    常用字符串方法
    方法

    说明

    upper() 返回字符串的大大写形式
    lower() 返回字符串的小写形式
    swapcase() 返回一个字符串,其中的大小写形式互换
    capitalize() 返回一个新的字符串,首字母大写
    title() 返回一个新的字符串,每个单词首字母大写
    strip() 返回一个新的字符串,原字符串首尾处的一切空白符(即制表符、空格、、换行等)都会被去掉
    replace(old,new,[,count]) 返回一个新的字符,原字符串中的old会被换成字符串new。如果给出了可选参数count计数,则只替换第一个计数出现次数
    class str(basestring):
        """
        str(object='') -> string
        
        Return a nice string representation of the object.
        If the argument is a string, the return value is the same object.
        """
        def capitalize(self):  
            """ 首字母变大写 """
            """
            S.capitalize() -> string
            
            Return a copy of the string S with only its first character
            capitalized.
            """
            return ""
    
        def center(self, width, fillchar=None):  
            """ 内容居中,width:总长度;fillchar:空白处填充内容,默认无 """
            """
            S.center(width[, fillchar]) -> string
            
            Return S centered 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):  
            """ 子序列个数 """
            """
            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 decode(self, encoding=None, errors=None):  
            """ 解码 """
            """
            S.decode([encoding[,errors]]) -> object
            
            Decodes S using the codec registered for encoding. encoding defaults
            to the default encoding. errors may be given to set a different error
            handling scheme. Default is 'strict' meaning that encoding errors raise
            a UnicodeDecodeError. Other possible values are 'ignore' and 'replace'
            as well as any other name registered with codecs.register_error that is
            able to handle UnicodeDecodeErrors.
            """
            return object()
    
        def encode(self, encoding=None, errors=None):  
            """ 编码,针对unicode """
            """
            S.encode([encoding[,errors]]) -> object
            
            Encodes S using the codec registered for encoding. encoding defaults
            to the default encoding. 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 is able to handle UnicodeEncodeErrors.
            """
            return object()
    
        def endswith(self, suffix, start=None, end=None):  
            """ 是否以 xxx 结束 """
            """
            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 expandtabs(self, tabsize=None):  
            """ 将tab转换成空格,默认一个tab转换成8个空格 """
            """
            S.expandtabs([tabsize]) -> string
            
            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):  
            """ 寻找子序列位置,如果没找到,返回 -1 """
            """
            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 format(*args, **kwargs): # known special case of str.format
            """ 字符串格式化,动态参数,将函数式编程时细说 """
            """
            S.format(*args, **kwargs) -> string
            
            Return a formatted version of S, using substitutions from args and kwargs.
            The substitutions are identified by braces ('{' and '}').
            """
            pass
    
        def index(self, sub, start=None, end=None):  
            """ 子序列位置,如果没找到,报错 """
            S.index(sub [,start [,end]]) -> int
            
            Like S.find() but raise ValueError when the substring is not found.
            """
            return 0
    
        def isalnum(self):  
            """ 是否是字母和数字 """
            """
            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):  
            """ 是否是字母 """
            """
            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 isdigit(self):  
            """ 是否是数字 """
            """
            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 islower(self):  
            """ 是否小写 """
            """
            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 isspace(self):  
    """如果字符串中只包含空格,则返回 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):  
            """
            S.istitle() -> bool
            
            Return True if S is a titlecased string and there is at least one
            character in S, i.e. uppercase characters may only follow uncased
            characters and lowercase characters only cased ones. Return False
            otherwise.
            """
            return False
    
        def isupper(self):  
            """
            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 join(self, iterable):  
            """ 连接 """
            """
            S.join(iterable) -> string
            
            Return a string which is the concatenation of the strings in the
            iterable.  The separator between elements is S.
            """
            return ""
    
        def ljust(self, width, fillchar=None):  
            """ 内容左对齐,右侧填充 """
            """
            S.ljust(width[, fillchar]) -> string
            
            Return S left-justified in a string of length width. Padding is
            done using the specified fill character (default is a space).
            """
            return ""
    
        def lower(self):  
            """ 变小写 """
            """
            S.lower() -> string
            
            Return a copy of the string S converted to lowercase.
            """
            return ""
    
        def lstrip(self, chars=None):  
            """ 移除左侧空白 """
            """
            S.lstrip([chars]) -> string or unicode
            
            Return a copy of the string S with leading whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            If chars is unicode, S will be converted to unicode before stripping
            """
            return ""
    
        def partition(self, sep):  
            """ 分割,前,中,后三部分 """
            """
            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 replace(self, old, new, count=None):  
            """ 替换 """
            """
            S.replace(old, new[, count]) -> string
            
            Return a copy of string 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 rfind(self, sub, start=None, end=None):  
    """类似于 find()函数,不过是从右边开始查找"""
    
            """
            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 rindex(self, sub, start=None, end=None):  
    """类似于 index(),不过是从右边开始"""
            """
            S.rindex(sub [,start [,end]]) -> int
            
            Like S.rfind() but raise ValueError when the substring is not found.
            """
            return 0
    
        def rjust(self, width, fillchar=None):  
    """返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串"""
            """
            S.rjust(width[, fillchar]) -> string
            
            Return S right-justified in a string of length width. Padding is
            done using the specified fill character (default is a space)
            """
            return ""
    
        def rpartition(self, sep):  
            """
            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 rsplit(self, sep=None, maxsplit=None):  
            """
            S.rsplit([sep [,maxsplit]]) -> list of strings
            
            Return a list of the words in the string 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 or is None, any whitespace string
            is a separator.
            """
            return []
    
        def rstrip(self, chars=None): 
    """删除字符串字符串末尾的空格""" 
            """
            S.rstrip([chars]) -> string or unicode
            
            Return a copy of the string S with trailing whitespace removed.
            If chars is given and not None, remove characters in chars instead.
            If chars is unicode, S will be converted to unicode before stripping
            """
            return ""
    
        def split(self, sep=None, maxsplit=None):  
            """ 分割, maxsplit最多分割几次 """
            """
            S.split([sep [,maxsplit]]) -> list of strings
            
            Return a list of the words in the string 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=False):  
            """ 根据换行分割 """
            """
            S.splitlines(keepends=False) -> 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 startswith(self, prefix, start=None, end=None):  
            """ 是否起始 """
            """
            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 strip(self, chars=None):  
            """ 移除两段空白 """
            """
            S.strip([chars]) -> string or unicode
            
            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.
            If chars is unicode, S will be converted to unicode before stripping
            """
            return ""
    
        def swapcase(self):  
            """ 大写变小写,小写变大写 """
            """
            S.swapcase() -> string
            
            Return a copy of the string S with uppercase characters
            converted to lowercase and vice versa.
            """
            return ""
    
        def title(self):  
            """
            S.title() -> string
            
            Return a titlecased version of S, i.e. words start with uppercase
            characters, all remaining cased characters have lowercase.
            """
            return ""
    
        def translate(self, table, deletechars=None):  
            """
            转换,需要先做一个对应表,最后一个表示删除字符集合
            intab = "aeiou"
            outtab = "12345"
            trantab = maketrans(intab, outtab)
            str = "this is string example....wow!!!"
            print str.translate(trantab, 'xm')
            """
    
            """
            S.translate(table [,deletechars]) -> string
            
            Return a copy of the string S, where all characters occurring
            in the optional argument deletechars are removed, and the
            remaining characters have been mapped through the given
            translation table, which must be a string of length 256 or None.
            If the table argument is None, no translation is applied and
            the operation simply removes the characters in deletechars.
            """
            return ""
    
        def upper(self):  
            """
            S.upper() -> string
            
            Return a copy of the string S converted to uppercase.
            """
            return ""
    
        def zfill(self, width):  
            """方法返回指定长度的字符串,原字符串右对齐,前面填充0。"""
            """
            S.zfill(width) -> string
            
            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 _formatter_field_name_split(self, *args, **kwargs): # real signature unknown
            pass
    
        def _formatter_parser(self, *args, **kwargs): # real signature unknown
            pass
    
        def __add__(self, y):  
            """ x.__add__(y) <==> x+y """
            pass
    
        def __contains__(self, y):  
            """ x.__contains__(y) <==> y in x """
            pass
    
        def __eq__(self, y):  
            """ x.__eq__(y) <==> x==y """
            pass
    
        def __format__(self, format_spec):  
            """
            S.__format__(format_spec) -> string
            
            Return a formatted version of S as described by format_spec.
            """
            return ""
    
        def __getattribute__(self, name):  
            """ x.__getattribute__('name') <==> x.name """
            pass
    
        def __getitem__(self, y):  
            """ x.__getitem__(y) <==> x[y] """
            pass
    
        def __getnewargs__(self, *args, **kwargs): # real signature unknown
            pass
    
        def __getslice__(self, i, j):  
            """
            x.__getslice__(i, j) <==> x[i:j]
                       
                       Use of negative indices is not supported.
            """
            pass
    
        def __ge__(self, y):  
            """ x.__ge__(y) <==> x>=y """
            pass
    
        def __gt__(self, y):  
            """ x.__gt__(y) <==> x>y """
            pass
    
        def __hash__(self):  
            """ x.__hash__() <==> hash(x) """
            pass
    
        def __init__(self, string=''): # known special case of str.__init__
            """
            str(object='') -> string
            
            Return a nice string representation of the object.
            If the argument is a string, the return value is the same object.
            # (copied from class doc)
            """
            pass
    
        def __len__(self):  
            """ x.__len__() <==> len(x) """
            pass
    
        def __le__(self, y):  
            """ x.__le__(y) <==> x<=y """
            pass
    
        def __lt__(self, y):  
            """ x.__lt__(y) <==> x<y """
            pass
    
        def __mod__(self, y):  
            """ x.__mod__(y) <==> x%y """
            pass
    
        def __mul__(self, n):  
            """ x.__mul__(n) <==> x*n """
            pass
    
        @staticmethod # known case of __new__
        def __new__(S, *more):  
            """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
            pass
    
        def __ne__(self, y):  
            """ x.__ne__(y) <==> x!=y """
            pass
    
        def __repr__(self):  
            """ x.__repr__() <==> repr(x) """
            pass
    
        def __rmod__(self, y):  
            """ x.__rmod__(y) <==> y%x """
            pass
    
        def __rmul__(self, n):  
            """ x.__rmul__(n) <==> n*x """
            pass
    
        def __sizeof__(self):  
            """ S.__sizeof__() -> size of S in memory, in bytes """
            pass
    
        def __str__(self):  
            """ x.__str__() <==> str(x) """
            pass
    str方法

     原始字符串

      原始字符串对于反斜线并不会特殊对待,在某些情况下这个特性是很有用的,在普通字符串中,反斜线有特殊的作用:它会转义,让你在字符串中加入通常情况下不能直接加入的内容。但是当我们不想字符串不反斜杠当成特殊字符时,原始字符串就派上用场了。原始字符串以r开头。

    >>> print("Hello,
    world")
    Hello,
    world
    
    #原始字符串
    >>> print(r"Hello,
    world")
    Hello,
    world
    View Code

    注意:不能在原始字符串结尾输入反斜线。因为如果最后一个字符是反斜线的话,Python就不清楚是否应该结束字符串。

      但如果我们希望原始字符只以一个反斜线作为结尾的话,可以对反斜线进行转义,本质上就是把反斜线单独作为一个字符串来处理。

    如:

    print(r'C:Program Filesfooar''\')
    C:Program Filesfooar

     基本字符串操作

      字符串是不可变的      

      所有标准的序列操作(索引、分片、乘法、判断成员资格、求长度、取最小值和最大值)对字符串也同样使用,上一章已经讲述了这些操作。但是,因为字符串是不可变的,倘若想对它分片赋值是不合法的:

    >>> website="http:\www.python.org"
    >>> website[-3:]
    'org'
    >>> website[-3:]="com"
    Traceback (most recent call last):
      File "<pyshell#18>", line 1, in <module>
        website[-3:]="com"
    TypeError: 'str' object does not support item assignment
    View Code

    字符串格式化:

    # 字符串的格式化
    name=input('name:')
    age=input('age:')
    job=input('job:')
    salary=input('salary:')
    #方法一
    info1="""
    
    -------info1 of %s -------
    name:%s
    age:%s
    job:%s
    salary:%s
    """%(name,name,age,job,salary)
    print(info1)
    
    #方法二
    info2="""
    
    ----------info2 of {_name}----------
    name:{_name}
    age:{_age}
    job:{_job}
    salary:{_salary}
    """.format(_name=name,_age=age,_job=job,_salary=salary)
    print(info2)
    
    #方法三
    info3="""
    
    --------info3 of {0}---------
    name:{0}
    age;{1}
    job:{2}
    salary:{3}
    
    """.format(name,age,job,salary)
    print(info3)
    
    name:Mike
    age:23
    job:IT
    salary:8000
    
    
    -------info1 of Mike -------
    name:Mike
    age:23
    job:IT
    salary:8000
    
    
    
    ----------info2 of Mike----------
    name:Mike
    age:23
    job:IT
    salary:8000
    
    
    
    --------info3 of Mike---------
    name:Mike
    age;23
    job:IT
    salary:8000
    View Code

    python字符串格式化符号:

        符   号描述
          %c  格式化字符及其ASCII码
          %s  格式化字符串
          %d  格式化整数
          %u  格式化无符号整型
          %o  格式化无符号八进制数
          %x  格式化无符号十六进制数
          %X  格式化无符号十六进制数(大写)
          %f  格式化浮点数字,可指定小数点后的精度
          %e  用科学计数法格式化浮点数
          %E  作用同%e,用科学计数法格式化浮点数
          %g  %f和%e的简写
          %G  %f 和 %E 的简写
          %p  用十六进制数格式化变量的地址

    格式化操作符辅助指令:

    符号功能
    * 定义宽度或者小数点精度
    - 用做左对齐
    + 在正数前面显示加号( + )
    <sp> 在正数前面显示空格
    # 在八进制数前面显示零('0'),在十六进制前面显示'0x'或者'0X'(取决于用的是'x'还是'X')
    0 显示的数字前面填充'0'而不是默认的空格
    % '%%'输出一个单一的'%'
    (var) 映射变量(字典参数)
    m.n. m 是显示的最小总宽度,n 是小数点后的位数(如果可用的话)

    find方法:

      可以在一个较长的字符串中查找子串。它返回子串所在的位置的最左端索引。如果没有找到则返回-1:

    >>> x="Hiding from the rain and snow"
    >>> x.find("a")
    17
    >>> x.find("v")
    -1
    View Code

    join方法:

      join方法是非常重要的字符串方法,它是split方法的逆方法,用来连接序列中的元素:

    #需要被连接的序列元素都必须是字符串
    >>> a=[1,2,3,4,5]
    >>> b="+"
    >>> b.join(a)  #字符串不能连接数字列表
    Traceback (most recent call last):
      File "<pyshell#11>", line 1, in <module>
        b.join(a)
    TypeError: sequence item 0: expected str instance, int found
    >>> a=['1','2','3','4','5']
    >>> b.join(a)   #可以连接字符串列表
    '1+2+3+4+5'
    
    >>> dirs='','user','bin','env'
    >>> '/'.join(dirs)
    '/user/bin/env'  #UNIX目录列表
    >>> print('C:'+'\'.join(dirs))
    C:userinenv  #Windows目录列表
    View Code

    translate方法

      translate方法和replace方法一样,可以替代字符串中的某些部分,但是和前者不同的是,translate方法只处理单个字符。它的优势在于可以同时进行多个替换,有些时候比replace效率高得多。使用这个方法的方式有很多(例如替换换行符或者其他因平台而已的特殊字符):

      在使用translate转换之前,需要先完成一张转换表。转换表中是以某字符替换某字符的对应关系。(转换表是包含替换ASCII字符集中256个字符的替换字母的)这个表我们不需要自己写,使用string模块里的maketrans函数就行了

      maketrans() 方法用于创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。注:两个字符串的长度必须相同,为一一对应的关系。

    >>> intab="aeiou"
    >>> outtab="12345"
    >>> trantab=str.maketrans(intab,outtab)
    >>> sing="""
    Hiding from the rain and snow
    Trying to forget but I won't let go
    Looking at a crowded street
    Listening to my own heart beat
    """
    >>> print(sing.translate(trantab))
    
    H3d3ng fr4m th2 r13n 1nd sn4w
    Try3ng t4 f4rg2t b5t I w4n't l2t g4
    L44k3ng 1t 1 cr4wd2d str22t
    L3st2n3ng t4 my 4wn h21rt b21t
    View Code
  • 相关阅读:
    Linux用户组管理及用户权限3
    MySQL预处理和事务
    MySQL-子查询和多表联查
    Mysql-分组和聚合函数
    LNMP搭建
    apache-虚拟主机配置
    Apache-重写
    apache配置文件详解
    vim使用
    php-curl_init函数
  • 原文地址:https://www.cnblogs.com/freely/p/6279749.html
Copyright © 2011-2022 走看看