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('你好'))
    '你好'
    >>>
    
  • 相关阅读:
    PowerShell 显示气球提示框 2
    BAT 删除隐藏文件
    批处理文件 bat 后台运行
    CMD 命令2
    CMD 命令1
    PowerShell 显示气球提示框 1
    查看SQL Server的版本及License
    How to extract a complete list of extension types within a directory?
    Wordpress无法连接Mysql8的问题
    What is `^M` and how do I get rid of it?
  • 原文地址:https://www.cnblogs.com/djdjdj123/p/14964971.html
Copyright © 2011-2022 走看看