How do I prepare a string for formatting with an ambiguous array?

Viewed 50

I need to format an array into a string, however the string is prepared and stored before hand. Essentially I have a list of strings that look something like this:

text = [
'Data Item 1: %.2f',
'Data Item 2: %.2f',
'Data Item 3: %.2f'
]

This list is then looped through and data is assigned to it similar to this:

for i in range(len(text)):
  print(text[i] % data[i])

This works fine but now I want to be able add a string to my text list which will later be paired with a list item like this:

text = [
'Data Item 1: %.2f',
'Data Item 2: %.2f',
'Data Item 3: %.2f',
'Num List: <FORMATTING NEEDED>'
]

data = [0.3, 2.1, 4.9, [1, 2, 3, 4]]

for i in range(len(text)):
  print(text[i] % data[i])

I want this to bear the following result:

Data Item 1: 0.30
Data Item 2: 2.10
Data Item 3: 4.90
Num List: 1,2,3,4

The closest thing to what I'm looking for that I have found so far looks like this:

'Num List: ['+", ".join(['%.2f']*len(x))+"]'

But I don't have 'x' yet. I need to prepare the string for a list that isn't immediately usable. I hope I explained my need correctly.

2 Answers

The result you show as desired doesn't have parentheses for the list, but in your attempt code you're using them so I'll assume they are ok.

In that case you could do something like:

print('Num List: %s' % [1,2,3,4])

which prints:

Num list: [1, 2, 3, 4]

I think you're most of the way there, would you be willing to just turn the array into a string, then include that in the data list?

doing this:

l = [1,2,3,4]
l_string = ",".join(str(x) for x in l)

results in a string that looks like this:

'0,1,2,3,4'

then you could just include that string in data, like this:

[0.3, 2.1, 4.9, ",".join(str(x) for x in l)]

you could also wrap this in a function depending on your application, maybe by checking for lists and converting them to strings. Then your test would look like this:

text = [
'Data Item 1: %.2f',
'Data Item 2: %.2f',
'Data Item 3: %.2f',
'Num List: %s'
]
Related