如何连接 python 中的字符串?

How to concatenate a string in python?

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

文件:

how
are
you

代码:

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

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

how
are
you

如何打印成单行?

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

print (line, end = "")

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

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

如果您使用 python 2.7,则以下语法应该有效:

print line,

标题要求拼接,细节要求输出。 print 答案处理后者,但如果您想连接,则可以使用 join+

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

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

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

要使 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))