3

As Joining a list that has Integer values with Python, the integer list can be joined by converting str and then joining them.

BTW, I want to get foo bar 10 0 1 2 3 4 5 6 7 8 9 where several data are first(foo, bar), then the size of list 10 and elements follows.

I used string.format as

x = range(10)
out = '{} {} {} {}'.format('foo', 'bar', len(x), x)

out will be foo bar 10 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

To solve problem I can rewrite the code as

out = '{} {} {} '.format('foo', 'bar', len(x)) + ' '.join([str(i) for i in x])

It looks inconsistent (mixed string.format and join). I tried

slot = ' {}' * len(x)
out = ('{} {} {}' + slot).format('foo', 'bar', len(x), *x)

It still unattractive I think. Is there a way to join integer list using string.format only?

Community
  • 1
  • 1
emesday
  • 6,078
  • 3
  • 29
  • 46

3 Answers3

5

I might be missing the point of your question, but you could simply extend the approach you link to as follows:

>>> x = range(10)
>>> out = " ".join(map(str, ["foo", "bar", len(x)] + x))
>>> out
'foo bar 10 0 1 2 3 4 5 6 7 8 9'
NPE
  • 486,780
  • 108
  • 951
  • 1,012
5

Since you favor attractiveness, want to use only one line and with format only, you can do

'{} {} {}{}'.format('foo', 'bar', len(x), ' {}' * len(x)).format(*x)
# foo bar 10 0 1 2 3 4 5 6 7 8 9
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
3

You can simply use the print function for this:

>>> from __future__ import print_function  #Required for Python 2
>>> print('foo', 'bar', len(x), *x)
foo bar 10 0 1 2 3 4 5 6 7 8 9
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504