python - How to pass tuple1 if ... else tuple2 to str.format? -
put simply, why following error?
>>> yes = true >>> 'no [{0}] yes [{1}]'.format((" ", "x") if yes else ("x", " ")) traceback (most recent call last): file "<stdin>", line 1, in <module> indexerror: tuple index out of range
i use python 2.6.
☞ indexing option:
when accessing arguments’ items in format string, should use index call value:
yes = true print 'no [{0[0]}] yes [{0[1]}]'.format((" ", "x") if yes else ("x", " "))
{0[0]}
in format string equals (" ", "x")[0]
in calling index of tulple
{0[1]}
in format string equals (" ", "x")[1]
in calling index of tulple
☞ *
operator option:
or can use *
operator unpacking argument tuple.
yes = true print 'no [{0}] yes [{1}]'.format(*(" ", "x") if yes else ("x", " "))
when invoking *
operator, 'no [{0}] yes [{1}]'.format(*(" ", "x") if yes else ("x", " "))
equals 'no [{0}] yes [{1}]'.format(" ", "x")
if if statement true
☞ **
operator option (it's method when var dict):
yes = true print 'no [{no}] yes [{yes}]'.format(**{"no":" ", "yes":"x"} if yes else {"no":"x", "yes":" "})
Comments
Post a Comment