首页 > 解决方案 > 将python中的名称大写

问题描述

有没有办法输入一个句子 str 并将其中的所有名称大写?

test_str = 'bitcoin is not dead and ethereum is cool'

我希望将其转换为

test_str = 'Bitcoin is not dead and Ethereum is cool'

这可能吗?我的第一个想法是使用 re 模块来定位名称然后修改它,但后来意识到名称似乎没有特定的模式。

标签: pythonregexpython-3.x

解决方案


如果您有要大写的单词列表,可以按如下方式进行:

names = ['bitcoin', 'ethereum']
test_str = 'bitcoin is not dead and ethereum is cool'
output_str = ' '.join([word.capitalize() if word in names else word for word in test_str.split()])

>>> 'Bitcoin is not dead and Ethereum is cool'

推荐阅读