I'm new to python and learning how to code. I'm printing last element of my list and sum of the list as-
print list[-1],sum
But the output is separated by " " and not separated by ",". Any idea how to separate it by comma?
I'm using Python 2.7
I'm new to python and learning how to code. I'm printing last element of my list and sum of the list as-
print list[-1],sum
But the output is separated by " " and not separated by ",". Any idea how to separate it by comma?
I'm using Python 2.7
Include it in quotes, like this:
print str(list[-1]) + "," + str(sum)
Enclosing them in str()
is unnecessary if list[-1]
and sum
are strings.
In general, symbols are interpreted as Python symbols (for example, names like sum
are interpreted as variable or function names). So whenever you want to print anything as is, you need to enclose it in quotes, to tell Python to ignore its interpretation as a Python symbol. Hence print "sum"
will print the word sum, rather than the value stored in a variable called sum
.
Use the sep
keyword argument:
print(list[-1], sum, sep=',')
You'll have to compose that together into a string. Depending on what version of Python you're using, you could either do:
print "{},{}".format(list[-1], sum)
or
print "%s,%s" % (list[-1], sum)
If you were using Python3.6+, there would be a third option:
print(f"{list[-1]},{sum}")
You can use str.format()
and pass whatever variables you want to get it formatted, for example:
x = 1
z = [1, 2, 3]
y = 'hello'
print '{},{},{}'.format(x, z[-1], y)
# prints: 1,3,hello