s = 'the brown fox'
...在这里做点什么……
S应为:
'The Brown Fox'
最简单的方法是什么?
s = 'the brown fox'
...在这里做点什么……
S应为:
'The Brown Fox'
最简单的方法是什么?
当前回答
大写的单词…
str = "this is string example.... wow!!!";
print "str.title() : ", str.title();
@Gary02127评论,下面的解决方案适用于带有撇号的标题
import re
def titlecase(s):
return re.sub(r"[A-Za-z]+('[A-Za-z]+)?", lambda mo: mo.group(0)[0].upper() + mo.group(0)[1:].lower(), s)
text = "He's an engineer, isn't he? SnippetBucket.com "
print(titlecase(text))
其他回答
正如Mark指出的,你应该使用.title():
"MyAwesomeString".title()
然而,如果你想让Django模板中的第一个字母大写,你可以这样做:
{{ "MyAwesomeString"|title }}
或者使用变量:
{{ myvar|title }}
当解决方案简单而安全的时候,为什么你要用连接和for循环来使你的生活复杂化?
只要这样做:
string = "the brown fox"
string[0].upper()+string[1:]
建议的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'
使用非均匀空格将字符串大写
我想补充一下@Amit Gupta关于非均匀空间的观点:
从最初的问题中,我们想要大写字符串s = 'the brown fox'中的每个单词。如果字符串s = 'the brown fox'有不均匀的空格。
def solve(s):
# If you want to maintain the spaces in the string, s = 'the brown fox'
# Use s.split(' ') instead of s.split().
# s.split() returns ['the', 'brown', 'fox']
# while s.split(' ') returns ['the', 'brown', '', '', '', '', '', 'fox']
capitalized_word_list = [word.capitalize() for word in s.split(' ')]
return ' '.join(capitalized_word_list)
如果访问[1:],空字符串将引发错误。因此我会使用:
def my_uppercase(title):
if not title:
return ''
return title[0].upper() + title[1:]
只大写第一个字母。