Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Integer list join using string.format

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?

like image 736
emeth Avatar asked Dec 01 '25 00:12

emeth


1 Answers

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
like image 108
thefourtheye Avatar answered Dec 03 '25 14:12

thefourtheye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!