• Python学习笔记3-字符串


    格式化字符串/复合字段名

    >>> import humansize
    >>> si_suffixes = humansize.SUFFIXES[1000]
    >>> si_suffixes
    ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
    
    
    >>> '1000{0[0]} = 1{0[1]}'.format(si_suffixes)
    '1000KB = 1MB'
    
    >>> import humansize
    >>> import sys
    >>> '1MB = 1000{0.modules[humansize].SUFFIXES[1000][0]}'.format(sys)
    '1MB = 1000KB'
    

    Sys.modules 是一个保存当前python实例中搜有已导入模块的字典。模块的名字为键,模块自身为值。

     
    
    >>> s = '''finished files are the re-
    
    sults of years of scientific study combined with the
    
    experience of years. ‘''
    
     
    
    >>> s.splitlines()
    
    ['finished files are the re-', 'sults of years of scientific study combined with the', 'experience of years. ‘]
    
     
    
    >>> print(s.lower())
    
    finished files are the re-
    
    sults of years of scientific study combined with the
    
    experience of years. 
    
     
    
    >>> a_list = query.split("&")
    
    >>> a_list
    
    ['user=pilgrim', 'database=master', ‘password=PapayaWhip']
    
     
    
    >>> a_list_of_list = [v.split('=',1) for v in a_list]
    
    >>> a_list_of_list
    
    [['user', 'pilgrim'], ['database', 'master'], ['password', ‘PapayaWhip']]
    
     
    
    >>> a_dict = dict(a_list_of_list)
    
    >>> a_dict
    
    {'password': 'PapayaWhip', 'database': 'master', 'user': ‘pilgrim'}
    

      

    split()-根据指定的分隔符,将字符串分隔成一个字符串列表。

    dict() - 将包含列表的列表转换成字典对象

    字符串的分片

    >>> a_string = "My alphabet starts where your alphabet ends."
    
    >>> a_string[3:11]
    
    ‘alphabet'
    
     
    
    >>> a_string[3:-3]
    
    'alphabet starts where your alphabet en’
    
     
    
    >>> a_string[:18]
    
    'My alphabet starts’
    
     
    
    >>> a_string[18:]
    
    ' where your alphabet ends.'
    

    String VS. Bytes

    Bytes对象的定义:b’ ’, eg: by = b’abcdx65’

    Bytes对象不能改变其值,但可以通过内置函数bytearry()将bytes对象转化成bytearry对象,bytearry对象的值可改变

     
    
    >>> by = b'abcdx65'
    
    >>> barr = bytearray(by)
    
    >>> barr
    
    bytearray(b'abcde')
    
     
    
    >>> barr[0]=102
    
    >>> barr
    
    bytearray(b'fbcde')
    
     
    
    >>> a_string = "dive into python"
    
    >>> by = a_string.encode('utf-8')
    >>> by
    b'dive into python'
    
    >>> roundtrip = by.decode('big5')
    >>> roundtrip
    'dive into python'
    

    string.encode() -- 使用某种编码方式作为参数,将字符串转化为bytes对象。

    bytes.decode() -- 使用某种编码方式作为参数,将bytes对象转化成字符串对象。

  • 相关阅读:
    Python面向对象:继承和多态
    Python面向对象:类、实例与访问限制
    Python正则表达式匹配猫眼电影HTML信息
    Git:从github上克隆、修改和更新项目
    Python:闭包
    JPA-映射-(@ManyToMany)双向多对多
    rownum详解
    java之yield(),sleep(),wait()区别详解
    springmvc<一>一种资源返回多种形式【ContentNegotiatingViewResolver】
    @RequestParam,@PathVariable,@ResponseBody,@RequestBody,@ModelAttribute学习
  • 原文地址:https://www.cnblogs.com/summerlong/p/4476010.html
Copyright © 2020-2023  润新知