在字符串中,大写所有的单词并留下其余的单词

时间:2011-01-09 20:08:22

标签: python

例如,完成了这个过程的字符串:

Hello, WORLD, McGisty, you are my HERO THAT I am.

应该返回/是:

Hello, World, McGisty, you are my Hero That I am.

2 个答案:

答案 0 :(得分:11)

>>> x = 'Hello, WORLD, McGisty, you are my HERO THAT I am.'
>>> m = ' '.join(e.capitalize() if e.isupper() else e for e in x.split())
>>> m
'Hello, World, McGisty, you are my Hero That I am.'

答案 1 :(得分:1)

使用re模块:

>>> import re
>>> x = 'Hello, WORLD, McGisty, you are my HERO THAT I am.'
>>> re.sub(r'[A-Z]+', lambda s: s.group().capitalize(), x)
'Hello, World, McGisty, you are my Hero That I am.'