9
어떻게 변수를 사용하여 변수를 포맷 할 수 있습니까?변수 서식이있는 파이썬의 형식 문자열
cart = {"pinapple": 1, "towel": 4, "lube": 1}
column_width = max(len(item) for item in items)
for item, qty in cart.items():
print "{:column_width}: {}".format(item, qty)
> ValueError: Invalid conversion specification
또는 내가 할 수있는 일
(...):
print "{:"+str(column_width)+"}: {}".format(item, qty)
> ValueError: Single '}' encountered in format string
하지만, 먼저 형식 문자열을 구성하고 포맷되어
(...):
formatter = "{:"+str(column_width)+"}: {}"
print formatter.format(item, qty)
> lube : 1
> towel : 4
> pinapple: 1
그러나, 서투른 보인다. 이런 상황을 처리하는 더 좋은 방법이 없을까요? 변수가 중첩 될 수 있습니다, 그래서 이것은 완벽하게 잘 작동 :
예,이 .format은()가'있다'하는 이유 중 하나입니다 '%'형식 문자열보다 선호 됨 –
@gnibbler :'% *'는 잘 작동합니다. – georg
Afaik'%'는 더 이상 사용되지 않으며 Python 3의 이후 버전에서는 제거되지 않습니다. 실제 마감일은 아직 알려지지 않았습니다. –