0

I want to remove the whitespace between each of the variables printed and replace them with commas.

In its current state, the string then each varable with a whitespace seperating them would be printed.

For example if a = 1 and each variable was an increase of 1 then this would be printed: 1 2 3 4 5 6 7 8 9. I want it to print: 1,2,3,4,5,6,7,8,9.

How can I do this?

Thanks.

Here is the code I'm trying to change:

print("Test: ", a,b,c,d,e,f,g,h,i)

3 Answers 3

2

Use str.join():

print('Test:', ','.join(map(str, [a, b, c, d, e, f, g, h, i])))

The map() call makes sure all values are strings first.

Demo:

>>> a, b, c, d, e, f, g, h, i = range(1, 10)
>>> print('Test:', ','.join(map(str, [a, b, c, d, e, f, g, h, i])))
Test: 1,2,3,4,5,6,7,8,9
Sign up to request clarification or add additional context in comments.

Comments

1

@Martijn's answer is the better way to do it, but just so you know this it's possible, the function print takes a keyword argument, sep, which specifies what to print between arguments between the function.

>>> print('Test:', a,b,c,d,e,f,g,h,i, sep=',')
Test:, 1,2,3,4,5,6,7,8,9

As you can see, it also prints a comma after "Test:", which is probably not what you want.

3 Comments

That's exactly why I deleted my answer that was identical to this :) The other albeit messy option is to print('Test': ', end='') and then print(a,b,c,d,e,f,g,h,i,sep=',')
Right! I would definitely opt for ",".join().
Thanks! If you're accepting this as the answer, I would appreciate it if you marked it as the "accepted answer" by clicking the checkmark next to it.
0

Joining iterables is one of the most frustrating things for newcomers to Python to learn. There is no join method for lists, for example.

The rationale is that this is a string method. It makes sense, since it returns a string.

However, a builtin join() function that takes an iterable and the string by which to join the items in it would make a lot of sense and get support from me.

The upside of Python, however, is that there are very few of these basic but counter-intuitive operations out there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.