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
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'
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.

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.