如何用Python把单行文本处理成两行并对齐?

 杜娟小乖_748 发布于 2022-10-26 16:16

][1]

[]内的文字新建一行秒自动对齐[]右边的文字。
如果一行内 只有一个[],一个中文占2个空格,英文占一个,就能做到,但如果出现多个[]就想不到了。

请教用python处理这样的问题应该怎么做呢?

谢谢!!

ps:[]内的字符不单一,有的是[F],有的可能是[Fm]、[Fmaj7]多个字符。

2 个回答
  • 另一个适应型更强的方法:

    outputChords = ""
    outputLyrics = ""
    inBracket = False

    for i in range(len(line)):

    if line[i] == '[':
        inBracket = True
        outputChords = outputChords + " " * (max(0, len(outputLyrics.encode('gbk')) - len(outputChords.encode('gbk'))))
    elif inBracket and line[i] == ']':
        inBracket = False
    elif inBracket and line[i] == '#':
        pass
    elif inBracket and str.isupper(line[i]):
        outputChords = outputChords + line[i]
    elif inBracket:
        # DONT TRANSPOSE AND PUT IN OUTPUTCHORDS
        outputChords = outputChords + line[i]
    else:
        outputLyrics = outputLyrics + line[i]
    2022-11-12 01:39 回答
  • python3

    设置字体为 等宽字体

    >>> s='[F]内的文字新建一行秒自动对齐[C]右边的文字'
    >>> import re
    >>> ptn=re.compile(r'\[([^]]+)\]([^[]+)')
    >>> ss='';t=''
    >>> for x,y in ptn.findall(s):
        ss+=('{:<%d}'% len(bytes(y,'gbk'))).format(x)
        t+=y
    
        
    >>> print(ss,t,sep='\n')
    F                         C         
    内的文字新建一行秒自动对齐右边的文字

    2022-11-12 01:39 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有