Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python .format() repeated fields?

I know in python3, you can do something like:

>>> '{0} {1} {0}'.format(13, 42)
'13 42 13'

So you're using the same argument multiple times. I'd like to do the opposite. I have a sequence of numbers. I'd like to somehow print them using a single format specifier, but I don't see a way to indicate to the format syntax that a given identifier should consume the next N arguments. I can use a reduce

>>> reduce(lambda out,x: out + '{:02X}'.format(x), b'\x60\x0d\x1a\xdd', '')
'600D1ADD'

But I was hoping for a single format invocation, as I had some other characters I wanted to place around my otherwise formatted sequence.

like image 668
Travis Griggs Avatar asked Jan 05 '13 05:01

Travis Griggs


People also ask

What does format () do in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

What does format .2f do in Python?

A format of . 2f (note the f ) means to display the number with two digits after the decimal point. So the number 1 would display as 1.00 and the number 1.5555 would display as 1.56 .

What does %s %d mean in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))

What is str format () in Python?

Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.


1 Answers

What about just something like this:

list = [13, 14, 42, 43]
out = ''.join([ '{0}'.format(x) for x in list ])

like image 142
derks Avatar answered Nov 05 '22 15:11

derks