使用python3打印字符串格式:从解压缩的数组*某些*时间打印 [英] String format printing with python3: print from unpacked array *some* of the time

查看:48
本文介绍了使用python3打印字符串格式:从解压缩的数组*某些*时间打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我几分钟前的问题中,我询问了如何使用 python 的 str.format 打印,当字符串存储在数组中时.

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))

但是如果我总是希望中心六边形打印在数组的第一个项目中:letters[0],我如何混合解包数组并保留第一个打印的字符串数组元素?

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?

我对其他印刷类型持开放态度,例如 f-strings.

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

例如:

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    )----'
          \       /
           \_____/

推荐答案

你可以用 .format() 尝试这样的事情:

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

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

将打印 3, 1, 2

使用这种方法,您的初始 hex_string 将自我记录"数组中的字母将精确到的位置.

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

这篇关于使用python3打印字符串格式:从解压缩的数组*某些*时间打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆