如何将字符串中每个单词的第一个字母大写? [英] How can I capitalize the first letter of each word in a string?

查看:55
本文介绍了如何将字符串中每个单词的第一个字母大写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

s = '棕色狐狸'

...在这里做点什么...

s 应该是:

'The Brown Fox'

最简单的方法是什么?

解决方案

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

这篇关于如何将字符串中每个单词的第一个字母大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆