> On Mar 3, 2017, at 13:42, dirkjso...@gmail.com <dirkjso...@gmail.com> wrote:
> 
> On 03/03/2017 12:19 PM, Alan Gauld via Tutor wrote:
>> 
>> That's one reason why join() is a better solution, it
>> handles all of that for you. It's also faster, although
>> in a small application you'd never notice the difference.
>> 
> The ','.join(suitcase) is obviously best of all, but if one doesn't know that 
> method, the below suggestion can be fixed with:
> 
> suitcase = ['book', 'towel', 'shirt', 'pants']
> 
> for i in suitcase:
>    st = st + i + ', '
> 
> print('You have a s% in your luggage.' % st)

There are three issues with that statement.
1. not knowing a method is not an excuse.  It’s worth knowing join because it 
has a lot of flexibility (and it _is_ known because of this discussion)
2. Your code as written doesn’t work because st is not defined before you use it

>>> suitcase = ['book', 'towel', 'shirt', 'pants']
>>> for i in suitcase:
...     st = st + i + ', '
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'st' is not defined

3. Your [fixed] code (added st = ‘') and join do NOT do the same thing (note 
the extra comma and space at the end of yours)
  join: You have a book, towel, shirt, pants in your luggage.
  yours: You have a book, towel, shirt, pants,  in your luggage.


String concatenation with a loop is notorious for adding extra stuff at the 
end.  To get it right, you have to take into account what to do at the end of 
the list, which adds code complexity.

—
David Rock
da...@graniteweb.com




_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to