zoukankan      html  css  js  c++  java
  • python基础教程:print()、str()和repr()的区别

    1.定义

    • print()函数,生成可读性更好的输出, 它会省去引号并打印
    • str()函数,用于将值转化为适于人阅读的字符串的形式
    • repr()函数,用于将值转化为供解释器读取的字符串形式

    print()函数,我们可以看出,在Python IDLE中直接输入的字符串都是有类型的,而print打印后的字符串相当于一串文字,把字符串的引号也省略了,没有类型

    2.实例

    >>>123
    123
    >>> type(123)
    <class 'int'>
    >>> print(123)
    123
    >>> type(print(123))
    123
    <class 'NoneType'>
    >>> '123'
    '123'
    >>>type('123')
    <class 'str'>
    >>> print('123')
    123
    >>> type(print( '123'))
    123
    <class "NoneType '>
    >>>
    

    str()函数,将值转化成字符串,但是这个字符串是人眼看到的,对人描述的字符串

    #遇到问题没人解答?小编创建了一个Python学习交流群:531509025
    #寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
    
    >>>123
    123
    >>> type(123)
    <class 'int'>
    >>> str(123)
    '123'
    >>>type(str(123))
    <class 'str'>
    >>> '123'
    '123'
    >>>type('123')
    <class 'str'>
    >>> str('123')
    '123'
    >>>type(str('123'))
    <class 'str'>
    >>>
    

    那么,python解释器读取的字符串又是什么呢?

    repr()函数能够为我们揭晓答案,repr()和str()的区别是,当值为字符串时,str()返回的是字符串本身'123',而repr()返回的是解释器读取的字符串," '123' "

    >>>123
    123
    >>> type(123)
    <class 'int'>
    >>> repr(123)
    '123'
    >>> type(repr(123))
    <class 'str'>
    >>> '123'
    '123'
    >>>type('123')
    <class 'str '>
    >>> repr('123')
    '123'
    >>> type(repr( '123'))
    <class 'str'>
    >>>
    

    结合三者,我们看个实例:

    • 原字符串输出是其本身
    • 加了print,输出去掉了''号
    • str('你好')输出是其本身,加了print,去掉了''号
    • repr('你好')输出是供解释器读取,输出为" '你好' ",print去掉了""号,因此最终输出为'你好'
    >>>'你好·你好'
    >>>print('你好')
    你好
    >>>print(str('你好'))
    你好
    >>>print(repr('你好'))
    '你好'
    >>>
    
  • 相关阅读:
    Shrink / VACUUM Database Sample Code C#
    (转)Export .NET MSChart to Excel/PDF Using Report Viewer 2010
    VS2010中使用《WeifenLuo.WinFormsUI.Docking.dll》,类型 Universe 无法解析程序集
    Binding to a ComboBox using a DataTable and Linq
    elementui 点击Switch开关弹出对话框确认后再改变switch开关状态
    c# 获取ip和mac
    mysql 允许ip访问
    jdk下载
    vue video 动态地址 不能自动播放
    c# 取右侧固定N个字符,不足用0填充
  • 原文地址:https://www.cnblogs.com/djdjdj123/p/14964971.html
Copyright © 2011-2022 走看看