python中英文混合字符串宽度对齐打印

中英文宽度对齐

def print_format(string,way,width,fill= ' ',ed = ''):#格式输出函数,默认格式填充用单空格,不换行。
    try:
        count = 0#长宽度中文字符数量
        for word in string:#检测长宽度中文字符
            if (word >='\u4e00' and word <= '\u9fa5') or word in [';',':',',','(',')','!','?','——','……','、','》','《']:
                count+=1
        width = width-count if width>=count else 0
        print('{0:{1}{2}{3}}'.format(string,fill,way,width),end = ed,flush=True)
    except:
        print('print_format函数参数输入错误!')
  • 该函数负责将中英文混合的字符串像英文字符串一样格式化输出,因为如果采用传统的 print 函数的格式化输出方法的话,中文汉字和一些中文字符(例如 《 》)的宽度为英文字符宽度的两倍,而 print 格式化输出是用英文单空格填充的,即使采用 chr(12288) 即中文单空格来填充的话也只能针对全为中文的字符串。
  • 我的这个字符串格式化输出函数的原理是将宽中文字符视为 2 个英文字符,对齐宽度依照英文字符的个数,通过检测字符串中的宽中文字符数量每一个宽中文字符实际对齐宽度减一,来实现中英文混合格式化输出
    该函数同样能自定义对齐方式,填充字符和结束字符

例程:

print_format('《深度学习》deep learning','^',30,'*','\n')
print_format('《C primer plus》4真好看','^',30,'*')

运行效果:
在这里插入图片描述

更新:多语言宽度对齐

在浏览其他博客时发现一个库:wcwidth,该库的一个函数 wcswidth 可以返回一个字符串的实际宽度,下面的代码在原本的代码上加入了该函数,使得可以进行多语言的宽度对齐打印。

wcwidth 库请自行安装

import wcwidth

def print_format(string,way,width,fill= ' ',ed = ''):#格式输出函数,默认格式填充用单空格,不换行。
    try:
        count = wcwidth.wcswidth(string)-len(string) #宽字符数量
        width = width - count if width >= count else 0
        print('{0:{1}{2}{3}}'.format(string,fill,way,width),end = ed,flush=True)
    except:
        print('print_format函数参数输入错误!')

例程:

print_format('《深度学习 deep learning》','^',30,'*','\n')
print_format('《C++ primer plus》','^',30,'*','\n')
print_format('日文 君の名は','^',30,'*','\n')
print_format('韩语 하늘의 3 분의 1은 파멸','^',30,'*')

运行效果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45715159/article/details/106176454
今日推荐