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

如何用colorama批量为Python字符串中的大写单词着色?

仅为答案中的大写单词添加青色标记(Python + Colorama)

问题场景

有20组类似answers_four的答案列表,需要给列表中每个字符串里的全大写单词(包括带撇号的,如DON'T)单独添加青色标记。手动逐个给目标单词加Fore.CYAN + "单词" + Fore.RESET效率太低,当前代码只能将整行答案染成青色,无法满足需求。

原始代码

import colorama
from colorama import Fore, Back, Style
colorama.init()

question_four = "\n4. 当你去世后,你最希望人们听到你的名字时做什么? \n"
answers_four = ["ASK for more stories about your adventures", "i DON'T CARE what people think of me after I'm dead, it's what they think of me while I'm alive that counts", "Think with ADMIRATION of your achievements", "MISS you, but smile"]

answers_house_a = ["ask", ...]
answers_house_b = ["don't care", ...]
answers_house_c = ["admiration", ...]
answers_house_d = ["miss", ...]

当前无效实现

for x in answers_four:
   print(f"{Fore.CYAN}" + x)

该代码会将整行答案全部染成青色,无法单独着色大写单词。

解决方案

使用正则表达式匹配全大写单词,批量替换为带颜色标记的格式,无需手动修改每个单词:

import colorama
import re
from colorama import Fore, Style
colorama.init()

# 正则规则:匹配全大写单词(支持含撇号的情况,如DON'T)
uppercase_pattern = re.compile(r'\b([A-Z]+(?:\'[A-Z]+)?)\b')

question_four = "\n4. 当你去世后,你最希望人们听到你的名字时做什么? \n"
answers_four = ["ASK for more stories about your adventures", "i DON'T CARE what people think of me after I'm dead, it's what they think of me while I'm alive that counts", "Think with ADMIRATION of your achievements", "MISS you, but smile"]

# 批量处理答案列表
for answer in answers_four:
    # 替换匹配到的大写单词,添加青色标记
    colored_answer = uppercase_pattern.sub(f'{Fore.CYAN}\\1{Style.RESET_ALL}', answer)
    print(colored_answer)

说明

  • 正则表达式r'\b([A-Z]+(?:\'[A-Z]+)?)\b'可以精准匹配全大写单词,包括DON'T这种带撇号的组合
  • re.sub()方法会自动遍历字符串,将所有匹配到的大写单词替换为带青色标记的版本,其他内容保持默认颜色
  • 此方法可直接复用在所有20组答案列表上,只需遍历对应列表即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:00:21