如何在Python中省略换行符?

时间:2016-07-18 06:24:07

标签: python

我知道.....在Python中用串联省略新行的一种方法:

a = 'strin'  
b = 2  
print str(b)+a  

我们可以通过多少方式完成这项工作?

3 个答案:

答案 0 :(得分:2)

我相信你使用的是Python2.x.您可以尝试以下操作:

  1. 使用尾随逗号。

     print a, # no new line will be printed
    
  2. 使用未来的打印功能

    from __future__ import print_function
    print(a,end='') # no new line will be printed
    
  3. 对于Python3.x以下将会这样做。 Do not need to import print function

         print(a,end='')
    

答案 1 :(得分:1)

你也可以试试这个,

print(repr(b), a) # ',' will avoid the newline

答案 2 :(得分:0)

是的,我终于找到了答案 我们可以省略3中的换行符:

  1. “+”(连接)
    例如:

    a = sachin
    b = 'tendulkar' 
    a += b 
    print(a)
    
  2. 使用“,”(逗号)见上述答案

  3. 使用 write()函数:

    import sys
    write = sys.stdout.write
    write('20)
    write('17')
    

    输出:

    2017
    

    write()方法不会在字符串末尾添加换行符('\ n')。