multiple prints on the same line in Python

前端 未结 17 2269
独厮守ぢ
独厮守ぢ 2020-11-22 06:06

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installi

17条回答
  •  盖世英雄少女心
    2020-11-22 06:34

    You can use the print statement to do this without importing sys.

    def install_xxx():
       print "Installing XXX...      ",
    
    install_xxx()
    print "[DONE]"
    

    The comma on the end of the print line prevents print from issuing a new line (you should note that there will be an extra space at the end of the output).

    The Python 3 Solution
    Since the above does not work in Python 3, you can do this instead (again, without importing sys):

    def install_xxx():
        print("Installing XXX...      ", end="", flush=True)
    
    install_xxx()
    print("[DONE]")
    

    The print function accepts an end parameter which defaults to "\n". Setting it to an empty string prevents it from issuing a new line at the end of the line.

提交回复
热议问题