Recently, I encountered a problem 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, centering works correctly!
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 is successfully completed!