【问题标题】:How to concatenate a string in python?如何在python中连接一个字符串?
【发布时间】:2015-12-15 05:37:40
【问题描述】:

我尝试读入一个文件并在一行中输出。

文件:

how
are
you

代码:

infile = open('input', 'r')
for line in infile:
    line = line.rstrip('\n')
    print (line)

rstrip 已经剥离 '\n', 但是输出仍然分为 3 行。

how
are
you

如何打印成单行?

【问题讨论】:

  • print (line, end = "")

标签: python string concatenation


【解决方案1】:

要使 2&3 兼容,您可以:

from __future__ import print_function
print('hello, world', end='')

所以你的代码可能是:

from __future__ import print_function
infile = open('input', 'r')
for line in infile:
    line = line.rstrip('\n')
    print(line, end='')

或者这个:

with open('input') as f:
    lines = [line.strip() for line in f.readlines()]
print(' '.join(lines))

【讨论】:

    【解决方案2】:

    标题要求连接,但细节只要求输出。 print 答案处理后者,但如果你想连接,那么你会使用 join+

    >>> with open('input', 'r') as infile:
    ...     output = ""
    ...     for line in infile:
    ...         output += line.rstrip('\n')
    ...     print(output)
    howareyou
    

    但是,鉴于您可能希望字符串之间有一个空格,那么我建议您查看join,它可以简单地与理解结合使用:

    >>> with open('input', 'r') as infile:
    ...     print(" ".join(line.rstrip(`\n`) for line in infile))
    how are you
    

    【讨论】:

      【解决方案3】:

      如果你使用 python 2.7,下面的语法应该可以工作:

      print line,
      

      【讨论】:

        【解决方案4】:

        去掉换行符后,只需将空字符串传递给print函数中的结束参数。

        print (line, end = "")
        

        print 默认情况下,每次迭代都会在新行中打印内容,但通过将空字符串传递给end 参数,此默认行为将不起作用。如果您未能删除换行符,它将与换行符一起打印内容。

        【讨论】:

        • 这仅适用于 Python 3.x 而不是 Python 2.x
        • 是的,操作使用print (,所以python 3的机会最大。
        【解决方案5】:

        因为每次循环运行时都会独立调用print() 函数。并且每次打印运行时,都会开始在新行上打印输出。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-07-06
          • 2016-01-17
          • 2022-12-17
          • 2015-05-02
          • 2016-10-19
          • 2016-08-08
          相关资源
          最近更新 更多