1

I'm having a tough time figuring out a solution to this one. I need to construct a single string with newlines that is built from a dynamic array. For example

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

The single text string will need to ultimately be this:

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

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

Here is the catch, the length of mylist is dynamic so TEXT must automatically adjust. So if mylist is this:

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

then my TEXT will automatically be this:

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

Appreciate any help

1
  • I'd look at using a for statement with the variables in mylist. Just keep in mind you may need to delete the last \n from the text string. Commented Nov 13, 2014 at 23:10

4 Answers 4

2

Use join:

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

To make it more dynamic, you can do it in a function, and call it whenever your list changes:

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
Sign up to request clarification or add additional context in comments.

1 Comment

@ChrisHall, not a problem, not being mean or anything, could you explain why you favour to another answer whereas my answer came first? Is that something to do with style?
1
mylist = ['first line', 'second line', 'third line', 'fourth line']
preamble = 'My preamble'
postamble = 'My postable'

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

print text

print text then produces the string in the following format:

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

Comments

0
"\n".join([preamble] + mylist + [postamble])

2 Comments

This is incorrect, consider if mylist is empty, your result will be missing 1 \n compared to OP's
that said, this is a more elegant way to use the join :)
0

Just in case your list contains other types than strings:

a=[10,11,12]
preamb='My Pre\n'
postam='My Pos'

Text=preamb
for i in a:
    Text += str(i)+'\n'
Text+=postam
print Text

Result:

My Pre
10
11
12
My Pos

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.