[Tutor] joining strings using arrays and string variables.

Cameron Simpson cs at cskk.id.au
Sun Feb 7 07:09:37 EST 2021


On 07Feb2021 22:06, Sean Murphy <mhysnm1964 at gmail.com> wrote:
>If I want to join a list that has a maximum of 5 elements plus two 
>strings variable. The below doesn't seem to work:
>
>>>> a = ['hello','fred','and','tom']

This is a flat list of str.

>>>> b = '/'.join(['welcome', 'the', 'following', a])

This tries to join a list of most-str, except for a, which is itself a 
list:

    ['welcome', 'the', 'following', ['hello','fred','and','tom']]

>Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>TypeError: sequence item 3: expected str instance, list found

That'll be a, which isn't a str, it is a list.

>>>> b = '/'.join('welcome', 'the', 'following', a)

Join expects a single iterable of strs. Not 4 arguments.

You probably want this:

    b = '/'.join(['welcome', 'the', 'following'] + a)

Nornmally I'd prepare all that before calling join:

    a = ['hello','fred','and','tom']
    a2 = ['welcome', 'the', 'following'] + a
    b = '/'.join(a2)

just for clarity rather than burying it inside the join() arguments.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Tutor mailing list