Python Keeps Alignment when Printing ASCII Characters Including Chinese

Introduction

When we print Python strings, we add spaces and tabs between words to align the output list or ASCII table.

For example, the following ASCII table

# ╔════╦════════╦═════════╦═══════╗
# β•‘ id β•‘  name  β•‘ course  β•‘ score β•‘
# ╠════╬════════╬═════════╬═══════╣
# β•‘  1 β•‘ Alex   β•‘ English β•‘    90 β•‘
# β•‘  2 β•‘ Elaine β•‘ Math    β•‘    92 β•‘
# β•‘  3 β•‘ Tom    β•‘ Science β•‘    88 β•‘
# β•‘  4 β•‘ Sophia β•‘ History β•‘    94 β•‘
# β•šβ•β•β•β•β•©β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•β•β•©β•β•β•β•β•β•β•β•

There is no problem when the strings are all in English, but once the string contains Chinese or other non-ASCII characters, it will be difficult to align.

World!!       β•‘ # 7 normal spaces
Helloδ½ ε₯½     β•‘ # 5 normal spaces
Helloδ½ ε₯½      β•‘ # 6 normal spaces

The reason is that the width of non-ASCII characters such as Chinese is larger than that of English letters, which requires special treatment for Chinese.

Analysis

In order to align ASCII characters, enough spaces are usually added to the character gap. The ordinary spaces " " belong to ASCII characters, and the Unicode code is U+0020, and if there are Chinese or Chinese punctuation marks, you need to use Chinese Full-width spaces to fill blanks, Unicode encoding U+3000.

Here we make a simple demonstration. When we recognize characters, after counting the length of Chinese characters, use the same length of ordinary spaces and the remaining length of full-width spaces to fill in. Equivalent to every ASCII character has a non-ASCII character pair, the length must be the same.

You can get the following output

Helloδ½ ε₯½  γ€€γ€€γ€€γ€€γ€€β•‘ # 2 normal spaces + 5 full-width spaces
World!!γ€€γ€€γ€€γ€€γ€€γ€€γ€€β•‘ # 7 full-width spaces

Code

import re

re_chinese = re.compile(r"[\u4e00-\u9fa5\!\?\。\οΌ‚\οΌ‡\(\οΌ‰\*\οΌ‹\,\-\/\:\οΌ›\<\=\>\οΌ \οΌ»\οΌΌ\οΌ½\οΌΎ\οΌΏ\ο½€\ο½›\|\}\~\⦅\ο½ \、\〃\γ€Š\》\γ€Œ\」\γ€Ž\』\【\】\γ€”\〕\γ€–\γ€—\γ€˜\γ€™\γ€š\γ€›\γ€œ\〝\γ€ž\γ€Ÿ\γ€°\γ€Ύ\γ€Ώ\–\β€”\β€˜\’\β€›\β€œ\”\β€ž\β€Ÿ\…\‧\﹏\.]", re.S)

def format_ascii(text) :
    t= re.findall(re_chinese,text)
    count = len(t)
    return text  + " " * count + u"\u3000" * (len(text) - count)


print(format_ascii("Helloδ½ ε₯½") + "β•‘")
print(format_ascii("World!!") + "β•‘")

Online Demo Python Online Editor

Conclusion

The above is about the Chinese string alignment problem encountered in Python development, which basically meets our development needs, and there may be some details that have not been noticed. You are welcome to put forward better ideas.

Reference

Comments