0

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

0

4 Answers 4

2

Use the sep keyword argument: print(list[-1], sum, sep=',')

Sign up to request clarification or add additional context in comments.

1 Comment

This only works in Python3. From the OP, print list[-1],sum is clearly using Python2.
2

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.

5 Comments

I did that but still there is space before and after comma. It prints like this 23 , 244 but I want it to be 23,244
See my edited answer.
also OP shouldn't use sum as a variable name as it's already the sum function.
@Jean-FrançoisFabre also OP shouldn't use list as a variable name as it's already the list constructor :)
Thanks a lot Antimony! It worked
2

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}")

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.