Trouble concatenating two strings

被刻印的时光 ゝ 提交于 2019-12-13 17:30:42

问题


I am having trouble concatenating two strings. This is my code:

info = infl.readline()
while True:
    line = infl.readline()
    outfl.write(info + line)
    print info + line

The trouble is that the output appears on two different lines. For example, output text looks like this:

490250633800 802788.0 953598.2
802781.968872 953674.839355 193.811523 1 0.126805 -999.000000 -999.000000 -999.000000

I want both strings on the same line.


回答1:


There must be a '\n' character at the end of info. You can remove it with:

info = infl.readline().rstrip()



回答2:


You should remove line breaks in the line and info variables like this : line=line.replace("\n","")




回答3:


readline will return a "\n" at the end of the string 99.99% of the time. You can get around this by calling rstrip on the result.

info = infl.readline().rstip()
while True:
    #put it both places!
    line = infl.readline().rstip()
    outfl.write(info + line)
    print info + line

readline's docs:

Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line)...



来源:https://stackoverflow.com/questions/7084937/trouble-concatenating-two-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!