且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将字符串中每个单词的第一个字母大写?

更新时间:2022-10-18 17:32:21

.title() 字符串的方法(ASCII 或 Unicode 都可以)这样做:

>>>你好世界".title()'你好,世界'>>>u你好世界".title()你好世界

但是,请注意带有嵌入撇号的字符串,如文档中所述.

该算法使用一个简单的独立于语言的单词定义为连续字母组.该定义在许多情况下都适用,但这意味着收缩和所有格中的撇号形成单词边界,这可能不是预期的结果:

>>>他们是比尔在英国的朋友".title()他们是比尔在英国的朋友"

s = 'the brown fox'

...do something here...

s should be:

'The Brown Fox'

What's the easiest way to do this?

The .title() method of a string (either ASCII or Unicode is fine) does this:

>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'

However, look out for strings with embedded apostrophes, as noted in the docs.

The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"