pythonstringtuplesstring-formattingiterable-unpacking

Tuple unpacking to formatted string in Python


I have been working though Fluent Python 2nd Edition by Luciano Ramalho.

On page 5 he writes that he has attempted to adopt the f string syntax throughout the book, although there are times when str.format() is better.

However in the below example he uses the % format to unpack a tuple:

traveler_ids = [('USA', '31195855'), ('BRA', 'CE342567'), ('ESP', 'XDA205856')]

# % operator
for passport in sorted(traveler_ids):
    print('%s/%s' % passport)

I managed to unpack the same tuple using the other two formatting methods, although the f string uses a , rather than a /. I got this f string solution from [SenhorLucas], using a comma to seperate however this is perhaps not as clear as the slash:

# str.format()
for passport in sorted(traveler_ids):
    print('{}/{}'.format(*passport))

# f string
for passport in sorted(traveler_ids):
    print(f'{*passport,}')

Questions

  1. First I was wondering, what is clearer in this case? Is there a difference in performance when using *passport?

  2. Secondly, is there a simple way to unpack using the same / divider in an f string?


Solution

  • You could unpack during enumeration of the sorted list which then makes f-string usage more straightforward :

    traveler_ids = [('USA', '31195855'), ('BRA', 'CE342567'), ('ESP', 'XDA205856')]
    
    for country, passport_number in sorted(traveler_ids):
        print(f"{country}/{passport_number}")
    
    # or, avoiding f-string and join (not a recommendation)...
    
    for country, passport_number in sorted(traveler_ids):
        print(country, passport_number, sep="/")