Fill in the Python string blank question.

Asked 2 years ago, Updated 2 years ago, 18 views

Hi, how are you?

I'd like to add a column to match the length of the variable. Please give me some advice.

For example,

You want to put text in a string with a total of eight digits, right-sort it, and then fill in the rest with spaces.

A = 'test' (4 compartments in front, 4 compartments in test - 8 compartments in total)

B='%8s'%A
len(B) = 8

print(B.encode('utf-8'))) = 8

A = 'Test' (5 compartments in front - 8 compartments in total)

B='%8s'%A

len(B) = 8

print(B.encode('utf-8'))) = 15 (8 + 6)

B='{0:0>8}'.format(A) rjsut The results are the same even if you try all the back.

I think it's an encoding problem. I took it with euckr, but the number of Korean characters decreased to 1byte It doesn't come within 8 digits, but it becomes 8+1 and 9 is taken.

python

2022-09-22 19:25

1 Answers

from wcwidth import wcswidth

def eaw_format_right(s, width, fill=' '):
    s_width = wcswidth(s)
    f_width = width - s_width
    if f_width < 0: f_width = 0
    fill = (fill*f_width)[:f_width]
    return fill + s

forxt in ['Korea', 'Korea']:
    print(eaw_format_right(txt, 8))

It's not a problem of encoding, but I think it's a problem that comes out because characters such as Hangul, Chinese characters, Japanese kana, and simplified Chinese characters occupy twice the place of ordinary alphabets or symbols. (I think it's called east Asian width.) Using the wcwidth function in wcwidth, it seems necessary to calculate how many digits a string occupies. Try running the example code above.


2022-09-22 19:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.