美文网首页Python
Python基础(1) - Print函数的用法

Python基础(1) - Print函数的用法

作者: xianling_he | 来源:发表于2020-02-17 20:53 被阅读0次

    使用sep参数设置字符串之间的分隔符,默认是空格

    • 在使用print方法的时候,可以加入sep参数,这个参数值默认是空格,当然可以使用其他的字符串。
    • 比如使用逗号(,)分隔
    #使用逗号分隔
    print("one","two",sep=",")
    

    使用end参数设置结尾符号,默认是换行符

    • 使用print 函数输出字符串,如何不换行
    • 以下是换按2行输出显示
    print("Hello")
    print("World")
    
    • 使用end将2行换行显示的内容,不换行显示
    print("Hello",end = " ")
    print("World")
    

    可以使用%格式化字符串

    • 如何用print函数格式化输出
    s = "road"
    x = len(s)
    print("The length of %s is %d" % (s,x))
    
    from io import StringIO
    import sys
    old_stdout = sys.stdout
    result = StringIO()
    sys.stdout = result
    print("The length of %s is %d" % (s,x))
    sys.stdout = old_stdout
    result_str = result.getvalue()
    print("result_str",result_str,sep=":")
    

    总结:

    1.使用sep参数设置字符串之间的分隔符,默认是空格
    2.使用end参数设置结尾符号,默认是换行符
    3.使用%格式化字符串
    4.使用StringIO() 进行重定向,将输出放到变量里面进行输出显示

    相关文章

      网友评论

        本文标题:Python基础(1) - Print函数的用法

        本文链接:https://www.haomeiwen.com/subject/izuifhtx.html