0

For instance, instead of something like:

My friends are Kate

My friends are Matt

I want to print out:

My friends are Kate, Matt

myFriends = []

def add_new_friend():
    while True:
        newFriend = input("Add your new friend (Enter blank to quit):")
        if newFriend == "":
            break
        elif newFriend == "check":
            check_friends()
        else:
            myFriends.append(newFriend)
            for friend in range(len(myFriends)):
                print(myFriends[friend])
Community
  • 1
  • 1
Nathan Natindim
  • 147
  • 2
  • 5

3 Answers3

4

Build the whole string that you want to print using join, then invoke print once:

print("My friends are " + ", ".join(myFriends))
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
1

This is one way. You can use str.format combined with ', '.join to print in the format you require.

myFriends = []

def add_new_friend():
    while True:
        newFriend = input("Add your new friend (Enter blank to quit):")
        if newFriend == "":
            break
        elif newFriend == "check":
            check_friends()
        else:
            myFriends.append(newFriend)
            print('My friends are: {0}'.format(', '.join(myFriends)))

add_new_friend()
jpp
  • 159,742
  • 34
  • 281
  • 339
  • The `{0}` is the last part of the format string. Does it have any advantages over a simple `+`, except that it is easier to change the formatting if the requirements change? *(it would be a perfectly valid reason, I see that. As soon as the OP wants to append a simple period, the `format` solution will become more concise)* – Andrey Tyukin Apr 02 '18 at 01:07
  • 1
    Some ([1](https://stackoverflow.com/questions/38722105/format-strings-vs-concatenation), [2](https://stackoverflow.com/questions/34619384/python-string-formatting-vs-concatenation)), including me, think `str.format` is more readable. This [good answer](https://stackoverflow.com/a/21542726/9209546) gives all the options. – jpp Apr 02 '18 at 01:15
0

You can also do the following

for friend in myFriends:
  print(friend, end=', ')

which should give you this output ...

Kate, Matt,