将两个字符串的串联附加到lis

2024-06-26 04:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张单子。我有两个字符串,比如说,“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”里。为了将输出重定向到文件,我运行了以下命令:

python clarbool.py>&燃气轮机;po.txt文件

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

如果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 " . 

中间添加换行符的原因是什么?如何获得预期的产出


Tags: 文件字符串pytxtanmostoutputis
3条回答
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

换行符是由print函数s default argument forend`添加的

可以这样称呼:

print("your string here", end="")

它能满足你的需求

根据文件:

Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

除了anuvrat的答案之外,在代码的末尾做print()

...
print()

注意:如果python的版本不是3,请在代码的顶行执行from __future__ import print_function

同样最好的是:

...
p.write(''.join(list_output))
print(''.join(list_output))

或:

...
p.write(''.join(list_output))
print(*list_output,sep='')

但如果版本不是3,则必须在代码顶部执行from __future__ import print_function

相关问题 更多 >