You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何将列表字符串首个冒号前内容设为粗体、后续内容正常显示

实现代码

import os
# Windows系统需要加这行开启ANSI转义码支持,非Windows系统可删除
os.system('')

class style:
    BOLD = "\033[1m"
    END = "\033[0m"

def Convert(string):
    li = list(string.split("\n\n"))
    return li

vocablist = ('''to remind s.o. (of sth./to do sth.): to put in mind of something: cause to remember

to remember sth.: to retain in the memory

to reject: to refuse to accept, hear, receive, or admit

to affirm: to assert as valid or confirmed; to show or express a strong belief in

universality: the quality of being true in or appropriate for all situations.

bias: a personal and sometimes unreasoned judgment; prejudice

implicit: present but not consciously held or recognized

conscious: perceiving or noticing with a degree of controlled thought or observation

assumption: an assuming that something is true

mundane: everyday, ordinary, routine

convention: usage or custom especially in social matters; an established practice

unconscious: not knowing or perceiving : not aware

normative: conforming to or based on norms OR dictating norms

imaginative: of, relating to, or characterized by imagination OR without truth

deviation: noticeable or marked departure from accepted norms

omnipresent: present in all places at all times

omnipotent: having virtually unlimited authority or influence; all-powerful
''')

# 拆分得到词条列表
item_list = Convert(vocablist)
processed_list = []

for item in item_list:
    if ':' in item:
        # 仅拆分第一个冒号,分割为前后两部分,避免释义中的冒号影响结果
        key, value = item.split(':', 1)
        processed_item = f"{style.BOLD}{key}{style.END}:{value}"
    else:
        # 无冒号的词条直接保留原内容
        processed_item = item
    processed_list.append(processed_item)
    # 直接打印即可看到粗体效果
    print(processed_item)

逻辑说明

  • split(':', 1)的第二个参数指定最大拆分次数为1,只会识别字符串里第一个出现的冒号做分割,完全符合你只加粗第一个冒号前内容的需求
  • 修正了原有代码中直接遍历原始字符串、列表append方法使用错误、索引逻辑错误的问题
  • 处理后的词条全部存储在processed_list中,可按需后续调用

内容的提问来源于stack exchange,提问作者1Noctis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 15:39:03