Printing String with Comma or Integer (Len's Slice Project)

Hey everyone! I was working through the Len’s Slice project. One of the questions required me to print a string including an integer. I managed to do it but I realized I was able to print the result in two ways.

  • The first was using a comma (,) between the string and integer
  • The second was using str(#)
    Which is considered the best way to do this?
    Thanks in advance! Here’s the code:
# toppings:
toppings = ["pepperoni", "pineapple", "cheese", "sausage", "olives", "anchovies", "mushrooms"]

# prices
prices = [2, 6, 1, 3, 2, 7, 2]

number_two_dollar_slices = prices.count(2)

num_pizzas = len(toppings)

print("We sell " + str(num_pizzas) + " different kinds of pizza!")
print("We sell", num_pizzas, "different kinds of pizza!")

That is preferable to comma separation since it is clearly one contiguous object once it is assembled. Commas do not indicate a relationship or connection and should not be used in production code.

You will have also discovered that we cannot concatenate different types, which is why your number had to be cast to a str.

Very soon you should be learning how to use string formatting which streamlines the process by eliminating concatenation and instead giving us interpolation templates. Following are three examples, oldest to newest…

# modulo formatting
print ("We sell %d different kinds of pizza!" % num_pizzas)
# str.format method
print ("We sell {} different kinds of pizza!".format(num_pizzas))
# f-string
print (f"We sell {num_pizzas} different kinds of pizza!")

None of the above require us to recast types, only tell the formatter what types to expect. %d tells Python to expect number digits.


Thank you for replying. I appreciate it!

1 Like