Python3基礎 內置函數 eval str轉爲list tuple dict

  •        Python : 3.7.3
  •          OS : Ubuntu 18.04.2 LTS
  •         IDE : pycharm-community-2019.1.3
  •       Conda : 4.7.5
  •    typesetting : Markdown

code

"""
@Author : 行初心
@Date   : 2019/7/7
@Blog   : www.cnblogs.com/xingchuxin
@Gitee  : gitee.com/zhichengjiu
"""


def main():
    # eval會把字符串的內容 當作 有效的表達式
    # 信息安全 -> eval不要直接執行用戶的輸入內容

    # 字符串的格式得對
    # txt文本存儲 數據信息 -> 讀取 轉換 應用

    # str -> list
    print(eval("['地漿','阿井泉','鹽膽水']"), type(eval("['地漿','阿井泉','鹽膽水']")))

    # str -> tuple
    print(eval("(1,2,3,4)"), type(eval("(1,2,3,4)")))

    # str -> dict
    print(eval("{'子':'鼠','醜':'牛','寅':'虎'}"), type(eval("{'子':'鼠','醜':'牛','寅':'虎'}")))


if __name__ == '__main__':
    main()

result

/home/coder/anaconda3/envs/py37/bin/python /home/coder/PycharmProjects/Base/demo.py
['地漿', '阿井泉', '鹽膽水'] <class 'list'>
(1, 2, 3, 4) <class 'tuple'>
{'子': '鼠', '醜': '牛', '寅': '虎'} <class 'dict'>

Process finished with exit code 0

source_code

def eval(*args, **kwargs): # real signature unknown
    """
    Evaluate the given source in the context of globals and locals.
    
    The source may be a string representing a Python expression
    or a code object as returned by compile().
    The globals must be a dictionary and locals can be any mapping,
    defaulting to the current globals and locals.
    If only globals is given, locals defaults to it.
    """
    pass

resource

  • [文檔 - English] docs.python.org/3
  • [文檔 - 中文] docs.python.org/zh-cn/3
  • [規範] www.python.org/dev/peps/pep-0008
  • [規範] zh-google-styleguide.readthedocs.io/en/latest/google-python-styleguide/python_language_rules
  • [源碼] www.python.org/downloads/source
  • [ PEP ] www.python.org/dev/peps
  • [平臺] www.cnblogs.com
  • [平臺] gitee.com


Python具備開源、跨平臺、解釋型、交互式等特性,值得學習。
Python的設計哲學:優雅,明確,簡單。提倡用一種方法,最好是隻有一種方法來作一件事。
代碼的書寫要遵照規範,這樣有助於溝通和理解。
每種語言都有獨特的思想,初學者須要轉變思惟、踏實踐行、堅持積累。python

相關文章
相關標籤/搜索