Pass sep="," as an argument to print()
You are nearly there with the print statement.
There is no need for a loop, print has a sep parameter as well as end.
>>> print(*range(5), sep=", ")
0, 1, 2, 3, 4
A little explanation
The print builtin takes any number of items as arguments to be printed. Any non-keyword arguments will be printed, separated by sep. The default value for sep is a single space.
>>> print("hello", "world")
hello world
Changing sep has the expected result.
>>> print("hello", "world", sep=" cruel ")
hello cruel world
Each argument is stringified as with str(). Passing an iterable to the print statement will stringify the iterable as one argument.
>>> print(["hello", "world"], sep=" cruel ")
['hello', 'world']
However, if you put the asterisk in front of your iterable this decomposes it into separate arguments and allows for the intended use of sep.
>>> print(*["hello", "world"], sep=" cruel ")
hello cruel world
>>> print(*range(5), sep="---")
0---1---2---3---4
Using join as an alternative
The alternative approach for joining an iterable into a string with a given separator is to use the join method of a separator string.
>>>print(" cruel ".join(["hello", "world"]))
hello cruel world
This is slightly clumsier because it requires non-string elements to be explicitly converted to strings.
>>>print(",".join([str(i) for i in range(5)]))
0,1,2,3,4
Brute force - non-pythonic
The approach you suggest is one where a loop is used to concatenate a string adding commas along the way. Of course this produces the correct result but its much harder work.
>>>iterable = range(5)
>>>result = ""
>>>for i, item in enumerate(iterable):
>>> result = result + str(item)
>>> if i > len(iterable) - 1:
>>> result = result + ","
>>>print(result)
0,1,2,3,4
Answer from Graeme Stuart on Stack OverflowPass sep="," as an argument to print()
You are nearly there with the print statement.
There is no need for a loop, print has a sep parameter as well as end.
>>> print(*range(5), sep=", ")
0, 1, 2, 3, 4
A little explanation
The print builtin takes any number of items as arguments to be printed. Any non-keyword arguments will be printed, separated by sep. The default value for sep is a single space.
>>> print("hello", "world")
hello world
Changing sep has the expected result.
>>> print("hello", "world", sep=" cruel ")
hello cruel world
Each argument is stringified as with str(). Passing an iterable to the print statement will stringify the iterable as one argument.
>>> print(["hello", "world"], sep=" cruel ")
['hello', 'world']
However, if you put the asterisk in front of your iterable this decomposes it into separate arguments and allows for the intended use of sep.
>>> print(*["hello", "world"], sep=" cruel ")
hello cruel world
>>> print(*range(5), sep="---")
0---1---2---3---4
Using join as an alternative
The alternative approach for joining an iterable into a string with a given separator is to use the join method of a separator string.
>>>print(" cruel ".join(["hello", "world"]))
hello cruel world
This is slightly clumsier because it requires non-string elements to be explicitly converted to strings.
>>>print(",".join([str(i) for i in range(5)]))
0,1,2,3,4
Brute force - non-pythonic
The approach you suggest is one where a loop is used to concatenate a string adding commas along the way. Of course this produces the correct result but its much harder work.
>>>iterable = range(5)
>>>result = ""
>>>for i, item in enumerate(iterable):
>>> result = result + str(item)
>>> if i > len(iterable) - 1:
>>> result = result + ","
>>>print(result)
0,1,2,3,4
You can use str.join() and create the string you want to print and then print it. Example -
print(','.join([str(x) for x in range(5)]))
Demo -
>>> print(','.join([str(x) for x in range(5)]))
0,1,2,3,4
I am using list comprehension above, as that is faster than generator expression , when used with str.join .
Videos
Hi!
I'm coding in Python for the first time, so forgive me if my question is pre-school basic.
Could someone explain what the difference is between using commas and pluses inside print()? I ask this because commas result in automatic spaces, whereas you have to add spaces inside each string when using pluses. See below
print(The product: " + product + " costs " + price + " dollars")
print("The product:", product, "costs", price, "dollars")To a newbie like me, it seems like using plus signs means a lot more work considering you have to manually input spaces. But I assume there is a syntactic (and perhaps also semantic) difference. Could someone enlighten me as to how these two separate lines of code differ from each other?
Thank you!
EDIT: I know that using plus means I have to change product -> str(product) and price -> str(product), but that just further proves my point... Doesn't it mean a lot more work?
In your second example, you're passing five arguments to print.print will then automatically convert all of its arguments to strings and print them separated with spaces. In your first example, you're building up one big string, and then passing it as a single argument to print. You can also use string formatting to a similar effect: print("The product: {} costs {} dollars".format(product, price)), or even print(f"The product: {product} costs {price} dollars") if you're using Python 3.6.
Beginner questions like this are usually more welcome at r/learnpython ;)
Locale-agnostic: use _ as the thousand separator
f'{value:_}' # For Python ≥3.6
Note that this will NOT format in the user's current locale and will always use _ as the thousand separator, so for example:
1234567 ⟶ 1_234_567
English style: use , as the thousand separator
'{:,}'.format(value) # For Python ≥2.7
f'{value:,}' # For Python ≥3.6
Locale-aware
import locale
locale.setlocale(locale.LC_ALL, '') # Use '' for auto, or force e.g. to 'en_US.UTF-8'
'{:n}'.format(value) # For Python ≥2.7
f'{value:n}' # For Python ≥3.6
Reference
Per Format Specification Mini-Language,
The
','option signals the use of a comma for a thousands separator. For a locale aware separator, use the'n'integer presentation type instead.
and:
The
'_'option signals the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type'd'. For integer presentation types'b','o','x', and'X', underscores will be inserted every 4 digits.
I'm surprised that no one has mentioned that you can do this with f-strings in Python 3.6+ as easy as this:
>>> num = 10000000
>>> print(f"{num:,}")
10,000,000
... where the part after the colon is the format specifier. The comma is the separator character you want, so f"{num:_}" uses underscores instead of a comma. Only "," and "_" is possible to use with this method.
This is equivalent of using format(num, ",") for older versions of python 3.
This might look like magic when you see it the first time, but it's not. It's just part of the language, and something that's commonly needed enough to have a shortcut available. To read more about it, have a look at the group subcomponent.