• python中各数据类型的转换整型/浮点型/str型/char型/list型/dict型 Marathon


    str -> int/float/list

    # 整型数字的字符串转化为数字 int/float
    strInt = "123"
    # str -> int
    strInt2Int = int(strInt)
    # str -> float
    strInt2Float = float(strInt)
    
    # 小数的字符串转化为数字 int/float
    strFloat = '12345.678'
    # str -> int, 截断小数部分,保留整数部分
    strFloat2Int = int(float(strFloat))
    # str -> float
    strFloat2Float = float(strFloat)
    
    #****************#
    

    num -> str

    # int -> str
    Int2String = str(123)
    # float -> str
    float2String = str(123.45)
    

    str <-> list

    # str -> list
    strFloat2List = list(strFloat)
    
    print(strFloat, strFloat2Int, strFloat2Float, strFloat2List)
    
    # list -> str
    # list必须是str类型的数组
    list2String = ''.join(['1', '2', '3', '4', '5', '.', '6', '7', '8'])
    

    char <-> num

    # char or byte -> num
    char2Int = ord('a')
    print(char2Int) # 97
    char2Int = ord('A')
    print(char2Int) # 65
    char2Int = ord('1')
    print(char2Int) # 49
    
    # num -> char
    num2Char = chr(97)
    print(num2Char)
    num2Char = chr(65)
    print(num2Char)
    num2Char = chr(49)
    print(num2Char)
    

    str <-> dict

    # 1. json
    import json
    jsonStr = '{"name" : "john", "gender" : "male", "age": 28}'
    jsonStr2Dict = json.loads(jsonStr)
    print(jsonStr2Dict, type(jsonStr2Dict))
    # {'name': 'john', 'gender': 'male', 'age': 28} <class 'dict'>
    dict2Json = json.dumps(jsonStr2Dict)
    print(dict2Json, type(dict2Json))
    # {"name": "john", "gender": "male", "age": 28} <class 'str'>
    
    # 2.eval
    str2Dict = eval('{"name" : "john", "gender" : "male", "age": 28}')
    print(str2Dict, type(str2Dict))
    # {'name': 'john', 'gender': 'male', 'age': 28} <class 'dict'>
    
    # 3. ast
    import ast
    str = "{'name': 'john', 'gender': 'male', 'age': 28}"
    str2Dict = ast.literal_eval(str)
    print(str2Dict, type(str2Dict))
    # {'name': 'john', 'gender': 'male', 'age': 28} <class 'dict'>
    
  • 相关阅读:
    h5手机页面注册处理(短信验证)
    jq倒计时
    Unity实现Android端视频播放
    Unity中自定义扩展方法
    UGUI中粒子特效与UI的遮挡问题
    Unity中各种格式计时器
    Unity中锚点的动态设置
    unity中调试模型时unity崩溃问题
    具体分析UGUI中RectTransform
    unity中加载场景不销毁以及切换场景重复实例化
  • 原文地址:https://www.cnblogs.com/davis12/p/15818545.html
Copyright © 2020-2023  润新知