s = 'the brown fox'
...在这里做点什么……
S应为:
'The Brown Fox'
最简单的方法是什么?
s = 'the brown fox'
...在这里做点什么……
S应为:
'The Brown Fox'
最简单的方法是什么?
当前回答
字符串的.title()方法(ASCII或Unicode都可以)这样做:
>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'
但是,请注意带有内嵌撇号的字符串,如文档中所述。
该算法使用一个简单的独立于语言的单词定义作为连续的字母组。这个定义在很多情况下都适用,但它意味着缩略词和所有格中的撇号形成了单词边界,这可能不是理想的结果: >>> "他们是比尔来自英国的朋友".title() “他们是比尔的英国朋友”
其他回答
我非常喜欢这个答案:
复制粘贴版本的@jibberia回答:
def capitalize(line):
return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])
但是我发送的一些行分离了一些空白的“字符,在尝试执行s[1:]时导致错误。可能有更好的方法,但我必须添加一个if len(s)>0,就像在
return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])
如果你只想知道第一个字母:
>>> 'hello world'.capitalize()
'Hello world'
但是每个单词都要大写:
>>> 'hello world'.title()
'Hello World'
建议的str.title()方法并非在所有情况下都有效。 例如:
string = "a b 3c"
string.title()
> "A B 3C"
而不是"A B 3c"
我认为,最好这样做:
def capitalize_words(string):
words = string.split(" ") # just change the split(" ") method
return ' '.join([word.capitalize() for word in words])
capitalize_words(string)
>'A B 3c'
你可以试试这个。简单而利落。
def cap_each(string):
list_of_words = string.split(" ")
for word in list_of_words:
list_of_words[list_of_words.index(word)] = word.capitalize()
return " ".join(list_of_words)
如果访问[1:],空字符串将引发错误。因此我会使用:
def my_uppercase(title):
if not title:
return ''
return title[0].upper() + title[1:]
只大写第一个字母。