gpt4 book ai didi

python - 从动态数组中构造一个带有新行的字符串

转载 作者:行者123 更新时间:2023-11-30 23:18:08 25 4
gpt4 key购买 nike

我很难找到解决这个问题的方法。我需要构造一个带有换行符的字符串,该字符串是从动态数组构建的。例如

mylist = ['first line', 'second line', 'third line', 'fourth line']

单个文本字符串最终需要是这样的:

preamble = 'My preamble'
postamble = 'My postable'

TEXT = preamble+'\n'+mylist[0]+'\n'+mylist[1]+'\n'+mylist[2]+'\n'+mylist[3]+'\n'+postamble

这里有一个问题,mylist 的长度是动态的,所以 TEXT 必须自动调整。所以如果我的列表是这样的:

mylist = ['first line', 'second line', 'third line']

那么我的文本将自动是这样的:

TEXT = preamble+'\n'+mylist[0]+'\n'+mylist[1]+'\n'+mylist[2]+'\n'+postamble

感谢任何帮助

最佳答案

使用加入:

TEXT = preamble + '\n' + '\n'.join(mylist) + '\n' + postamble

TEXT
'My preamble\nfirst line\nsecond line\nthird line\nfourth line\nMy postable'

print TEXT

My preamble
first line
second line
third line
fourth line
My postable
<小时/>

为了使其更加动态,您可以在函数中执行此操作,并在列表更改时调用它:

def get_TEXT():
return preamble + '\n' + '\n'.join(mylist) + '\n' + postamble

mylist.append('fifth line')

get_TEXT()
'My preamble\nfirst line\nsecond line\nthird line\nfourth line\nfifth line\nMy postable'

print get_TEXT()

My preamble
first line
second line
third line
fourth line
fifth line
My postable

关于python - 从动态数组中构造一个带有新行的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26920136/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com