在Python中将大写字符串转换为句子大小写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39969202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 23:00:12  来源:igfitidea点击:

Convert UPPERCASE string to sentence case in Python

python

提问by MoreScratch

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:

使用titlecase(str)给了我:

"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?

是否有捷径可寻?

回答by brianpck

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

让我们为此使用一个更合适的函数: string.capitalize

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

回答by Zizouz212

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 结尾,.否则不会被视为新句子。(窃取.capitalize()哪种方法更好,为此向 brianpck 致敬)

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