zoukankan      html  css  js  c++  java
  • python—内置函数-字符串,eval,isinstance

    eval()

      功能:将字符串str当成有效的表达式来求值并返回计算结果。

      语法: eval(source[, globals[, locals]]) -> value

      参数:

        source:一个Python表达式或函数compile()返回的代码对象

        globals:可选。必须是dictionary

        locals:可选。任意map对象

      实例展示:

    可以把list,tuple,dict和string相互转化。
     #################################################
    字符串转换成列表
    >>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
    >>>type(a)
    <type 'str'>
    >>> b = eval(a)
    >>> print b
    [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
     >>> type(b)
    <type 'list'>
     #################################################
    字符串转换成字典
    >>> a = "{1: 'a', 2: 'b'}"
    >>> type(a)
    <type 'str'>
     >>> b = eval(a)
     >>> print b
    {1: 'a', 2: 'b'}
    >>> type(b)
    <type 'dict'>
     #################################################
    字符串转换成元组
    >>> a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
    >>> type(a)
    <type 'str'>
    >>> b = eval(a)
    >>> print b
    ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
    >>> type(b)
     <type 'tuple'>
    
    

    isinstance()
    def isAString(obj):
        return isinstance(obj, str)
    
    if isAString('1'):
        print('是字符串')
  • 相关阅读:
    10.23继承
    10.22语法 class 类 面向对象概念 类与对象 对象的使用 绑定方法
    10.18
    10.16
    读书笔记-软技能:代码之外的生存指南
    git reset
    阿里云安装samba
    关于svn由于目标计算机积极拒绝,无法连接的解决办法
    yii2简单安装
    指定路径创建中文文件名并存入内容
  • 原文地址:https://www.cnblogs.com/xiaobai-yemao/p/9153314.html
Copyright © 2011-2022 走看看