Python standard library: Formatting strings

preview_player
Показать описание


Subscribe to this channel, as I try to go through all of the Python standard library!
Рекомендации по теме
Комментарии
Автор

Hi Reuven, follow up question for you. Here is an example that prints text as column headers three different ways. I want to use the first method because it is a cleaner way of set the column width dynamically. The second method uses hard coded values, which makes the code less flexible. But the third method is uses a lot of concatenation which makes the code less readable. However, the second and third methods are the only methods that work. The first method doesn’t work, but why? Is there a cleaner way to set column width dynamically?

w1 = '25'
w2 = '15'
headers = ('First', 'Last')

template = f'|{0:^{w1}}|{1:^{w2}}|'


template = '|{0:^25}|{1:^15}|'


template = '|{0:^' + w1 + '}|{1:^' + w2 + '}|'

cetilly
Автор

Your keyboard sounds awesome. What model and/or keys are you using?

CrapE_DM
Автор

What about performing these same actions on string literals, e.g. a string that is a list of column headers that you want to be the same formatting as the data which will come in as variables? Possible?

cetilly