Convert UPPERCASE string to sentence case in Python

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

How does one convert an uppercase string to proper sentence-case? Example string:

"OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE" 

Using titlecase(str) gives me:

"Operator Fail to Properly Remove Solid Waste" 

What I need is:

"Operator fail to properly remove solid waste" 

Is there an easy way to do this?

回答1:

Let's use an even more appropriate function for this: string.capitalize

>>> s="OPERATOR FAIL TO PROPERLY REMOVE SOLID WASTE" >>> s.capitalize() 'Operator fail to properly remove solid waste' 


回答2:

This will work for any sentence, or any paragraph. Note that the sentence must end with a . or it won't be treated as a new sentence. (Stealing .capitalize() which is the better method, hats off to brianpck for that)

a = 'hello. i am a sentence.' a = '. '.join(i.capitalize() for i in a.split('. ')) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!