Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String format printing with python3: print from unpacked array *some* of the time

In my question a few minutes ago, I asked about how to print using python's str.format printing, when the strings are stored in an array.

Then answer was clearly unpack the list, like this:

# note that I had to play with the whitespace because the {} text is 2 characters, while its replacement is always one

hex_string = r'''
            _____
           /     \
          /       \
    ,----(    {}    )----.
   /      \       /      \
  /   {}    \_____/   {}    \
  \        /     \        /
   \      /       \      /
    )----(    {}    )----(
   /      \       /      \
  /        \_____/        \
  \   {}    /     \   {}    /
   \      /       \      /
    `----(    {}    )----'
          \       /
           \_____/
'''

letters = list('1234567')

print(hex_string.format(*letters))

But if I always want the center hexagon to have printed inside the first item in the array: letters[0], how can I mix unpacking the array with keeping the 4th printed string from the first array element?

I'm open to other printing types, like f-strings.

For example:

print(hex_string.format(letters[3], letters[1], letters[2], letters[0], letters[4], letters[5], letters[6]))

So that my output actually looks like this:

            _____
           /     \
          /       \
    ,----(    4    )----.
   /      \       /      \
  /   2    \_____/   3    \
  \        /     \        /
   \      /       \      /
    )----(    1    )----(
   /      \       /      \
  /        \_____/        \
  \   5    /     \   6    /
   \      /       \      /
    `----(    7    )----'
          \       /
           \_____/
like image 278
philshem Avatar asked May 11 '19 17:05

philshem


2 Answers

You can try something like this with .format():

a = '123'
print('{2}, {0}, {1}'.format(*a))

which would print 3, 1, 2

With this approach, your initial hex_string will "self document" where the letters from your array will go exactly.

like image 109
Faboor Avatar answered Oct 20 '22 10:10

Faboor


If you know the required order beforehand:

letters = list('1234567')
reordering = [4,2,3,1,5,4,7]

You can apply this to the letters:

new_letters = [letters[index-1] for index in reordering]

Output:

['4', '2', '3', '1', '5', '4', '7']

Now you can create your formatted string:

print(hex_string.format(*new_letters))
like image 31
quamrana Avatar answered Oct 20 '22 10:10

quamrana