I’m having trouble understanding why an inner loop in my method isn’t producing the desired behavior I’m expecting and I’m hoping someone can help me understand the problem.
My method takes a series of arguments (*args) and if the argument is an integer I want to add dollar signs around the integer (eg. $5$).
def t_row(*args):
columns = 5
if len(args) == columns:
count = 0
for value in args:
if type(value) is int:
value = ''.join(('$', str(value), '$'))
count += 1
if count < len(args):
penult_args = args[:-1]
line_prefix = [''.join((str(value), " & ")) for value in penult_args]
elif count == len(args):
line_suffix = [''.join((str(value), " \\\\", "\n"))]
count += 1
line_list = line_prefix + line_suffix
line = ''.join(item for item in line_list)
return(line)
The above code is used like this:
>>> s = q.t_row('data1', 'data2', 3, 'data4', 5)
>>> print s
data1 & data2 & 3 & data4 & $5$ \\
Why don’t I get dollar signs around the integer 3? How can I fix my code to correct this problem?
Because on this line:
you pull the values out of the original list (minus the last item), while on this line:
You added
$but never stored the value back into the list.The
5only gets$because it’s the last item, so you reference it directly in:A better way to do all this is:
As a one-liner, it would be
but that’s not actually a good idea.