amtoaer

晓风残月

叹息似的渺茫,你仍要保存着那真!
github
x
telegram
steam
nintendo switch
email

Centering Chinese strings in Python

I recently encountered an issue while implementing a small feature: centering strings.

Although Python has a built-in string method string.center(), which allows strings to be centered, it does not handle Chinese strings properly and fails to achieve the desired centering effect.

Later, I suddenly realized that it might be due to the issue with the length of Python strings. I tested it with the following code:

str1 = '哈哈哈'
str2 = 'hhh'
print(len(str1), '+', len(str2))

The output is unexpectedly 3+3, which means that Python considers each Chinese character/letter as one character, even though their widths are different. This calculation inevitably leads to incorrect centering. The key is to distinguish Chinese characters, so I manually wrote a centering function:

def strCenter(str, len):
    lst = list(str)
    length = 0
    for item in lst:
        if item in string.printable:
            length += 1
        else:
            length += 2
    count = int((len - length) / 2)
    result = count * ' ' + str + count * ' '
    return result

Now, it can center properly!

Let's test it with the following additional content:

a = '哈a哈a哈a哈a'
b = '12345678901234567890'
print(a.center(20))
print(b.center(20))
print(20 * '-')
print(strCenter(a, 20))
print(strCenter(b, 20))

The output is:

      哈a哈a哈a哈a      
12345678901234567890
--------------------
    哈a哈a哈a哈a    
12345678901234567890

The task has been successfully completed!

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.