Search code examples
pythonpython-3.xlistunpack

How to print a string before using "*" to unpack list


Is it possible to print a string before using the * operator when unpacking a tuple:

m = ['b', 'a', 'e']
print(*m, sep = ',')

b, a, e

I tried to print something before it:

print("String: " + *m, sep = ",")

My desired output would be:

String: b, a, e

Is it possible to have a string print before this, and what would be the correct syntax?


Solution

  • *m unpacks the list m into separate arguments. It's equivalent to:

    print('b', 'a', 'e')
    

    You can add additional arguments before and after that:

    print('string', *m, sep=',')
    

    is it possible to print that without the comma being after the string, and only having the comma apply to the items in the list?

    Take your pick:

    print(f'String: {", ".join(m)}')
    
    print('String:', ', '.join(m), sep=' ')
    
    print('String:', end=' ')
    print(*m, sep=', ')