我试图在Python中打印日语字符,并使其对齐成列。似乎日语字符的宽度相当于两个空格,因此对齐无法正常工作。
以下是代码:
def print_kanji(s, k):
print('{:<20}{:<10}{:<10}{:<10}'
.format(s, k['reading'][0], k['reading'][1], k['kanji']))
# Being 's' some input string and 'k' a map which contains readings in the 3 different japanese alphabets.
我得到的输出如下:
decir いう イウ 言う
pequeño すくない スクナイ 少ない
niño こども コドモ 子供
ya [ha hecho X] もう モウ
左侧列是西班牙语,但这不重要。重要的是右侧的3列没有对齐。我已经计算了位置数,它是正确的,也就是说,第一列日文始终为10个“位置”长,问题在于日文字形是2个位置宽,而空格只有1个位置。 我也已经检查过,使用日语输入法时,一个空格也是两个位置宽,因此我应该能够通过将“拉丁”空格(1个位置宽)替换为日文空格来解决问题。
如何更改
format
将用于对齐字符串的字符?编辑
我发现
str.format
有一个名为fill
的参数。我尝试用日文空格(两个位置宽)替换它,结果更糟糕了。编辑2
我通过实现这个函数解决了它。
def get_formatted_kanji(h, k, kn):
h2 = h + str(' ' * (10 - 2*len(h)))
k2 = k + str(' ' * (10 - 2*len(h)))
kn2 = kn + str(' ' * (10 - 2*len(h)))
return h2 + k2 + kn2
# being h, k and kn the three 'japanese strings' to be formatted in columns
然而,有没有更好的(内置的)方法来实现这个?