Python print打印不换行

2/13/2017来源:经验技巧人气:1903

Python中的PRint默认是换行的

想要不换行输出有两种办法:

1.print后加上","

############################

>>>print "Hello World",

############################

2.使用sys.stdout.write命令

############################

>>>sys.stdout.write("Hello World")

############################

 

但是,以上的命令在具体执行时,并不会实时显示,每次都是在换行时才把整行指令打出来.

如果要实时显示,需要在每次sys.stdout.write后面加上一行sys.stdout.flush()让屏幕输出

############################

sys.stdout.write("Hello World")

sys.stdout.flush()

sys.stdout.write("one line!")

sys.stdout.flush()

############################

 

附一段我用来控制write换行情况的代码

############################

class ChangeLine:     NewLine = True     @classmethod     def write_out(self,str,typename = 0): #   0 is "\n.....\n"         if typename == 0:             if self.NewLine == False:                 sys.stdout.write('\n')                 sys.stdout.flush()             sys.stdout.write(str + '\n')             sys.stdout.flush()             self.NewLine = True #   1 is "......."         if typename == 1:             sys.stdout.write(str)             sys.stdout.flush()             self.NewLine = False #   2 is "\n......"         if typename == 2:             if self.NewLine == False:                 sys.stdout.write('\n')                 sys.stdout.flush()             sys.stdout.write(str)             sys.stdout.flush()             self.NewLine = False #   3 is "......\n"         if typename == 3:             sys.stdout.write(str + '\n')             sys.stdout.flush()             self.NewLine = True

############################