首页 > 解决方案 > 将两个字符串的串联附加到列表中

问题描述

让我们说,我有一个清单。而且我有两个字符串,比方说,“abc”和“ced”,我想将这两个字符串的串联附加到 python 中的列表中,例如“abcced”。

我有以下代码片段:

     if t == 1 :
       j = n + " ifcnt " + str(ifcnt)
       lst_output.append(j)
    else :
       lst_output.append(n)

p = open("po.txt" , 'w')

for i in lst_output :
    p.write(i)
    print(i)

我把它保存在一个文件 "bool.py" 中。为了将输出重定向到文件,我运行了以下命令:

蟒蛇 clarbool.py >> po.txt 。

但是,对于附加两个字符串的行,我得到的输出如下:

if n = "出局是我们想要的最有趣的事情"

"an out is  a single most interesting thing that we want " 
"ifcnt 5 "   

附加的字符串正在正确添加,但显然中间有一个换行符。

我期望的输出是:

"an out is  a single most interesting thing that we want ifcnt 5 " . 

在两者之间添加换行符的原因是什么?如何获得预期的输出?

标签: python

解决方案


p.write(lst_output[0] + lst_output[1])

演示:

n = 'an out is a single most interesting thing that we want '
a = 'ifcnt 5'

l = [n, a]
print(l[0] + l[1])
an out is a single most interesting thing that we want ifcnt 5

推荐阅读