1

I want to format a string in Python, and as one element have every element of a list, for example below

mylist = ['john','phil','ted']
var1 = 'xxx'
var2 = 'zzz'
'{0} bla bla bla {1} bla bla {2}'.format(var1,<every item in mylist>,var2)

Basically what I am after is

xxxx bla bla bla john phil ted bla bla zzz
thefourtheye
241k53 gold badges466 silver badges505 bronze badges
asked Mar 25, 2015 at 14:06
0

2 Answers 2

3

You can join all the strings in the list and pass like this

>>> mylist, var1, var2 = ['john','phil','ted'], 'xxx', 'zzz'
>>> '{0} bla bla bla {1} bla bla {2}'.format(var1, " ".join(mylist), var2)
'xxx bla bla bla john phil ted bla bla zzz'
answered Mar 25, 2015 at 14:07
Sign up to request clarification or add additional context in comments.

1 Comment

Hi thefourtheye, yes this worked for me perfectly. I couldn't find an exact similar question on stack so thanks for your assistance :)
2

I find % more concise than format.

'%s bla bla bla %s bla bla %s' % (var1, ' '.join(mylist), var2)

As already stated, you can join every item in mylist to turn it into a string.

answered Mar 25, 2015 at 14:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.