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 }}
只是因为这类事情对我来说很有趣,这里还有两个解决方案。
拆分为单词,从拆分的组中为每个单词加首字母大写,然后重新连接。这将把分隔单词的空白改为一个单独的空白,不管它是什么。
s = 'the brown fox'
lst = [word[0].upper() + word[1:] for word in s.split()]
s = " ".join(lst)
编辑:我不记得当我写上面的代码时我在想什么,但是没有必要构建一个显式的列表;我们可以使用生成器表达式以惰性方式来执行此操作。所以这里有一个更好的解决方案:
s = 'the brown fox'
s = ' '.join(word[0].upper() + word[1:] for word in s.split())
Use a regular expression to match the beginning of the string, or white space separating words, plus a single non-whitespace character; use parentheses to mark "match groups". Write a function that takes a match object, and returns the white space match group unchanged and the non-whitespace character match group in upper case. Then use re.sub() to replace the patterns. This one does not have the punctuation problems of the first solution, nor does it redo the white space like my first solution. This one produces the best result.
import re
s = 'the brown fox'
def repl_func(m):
"""process regular expression match groups for word upper-casing problem"""
return m.group(1) + m.group(2).upper()
s = re.sub("(^|\s)(\S)", repl_func, s)
>>> re.sub("(^|\s)(\S)", repl_func, s)
"They're Bill's Friends From The UK"
我很高兴我研究了这个答案。我不知道re.sub()可以接受函数!您可以在re.sub()中进行非平凡的处理以产生最终结果!
不要忽视空白的保留。如果你想处理“fred flinstone”,你得到的是“fred flinstone”而不是“fred flinstone”,你已经破坏了你的空白空间。上面的一些解决方案会丢失空白。这里有一个解决方案,适用于Python 2和3,并保留了空白。
def propercase(s):
return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))
.title()方法不能很好地工作,
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
试试string.capwords()方法,
import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
来自Python capwords文档:
使用str.split()将参数拆分为单词,使用str.capitalize()将每个单词大写,并使用str.join()连接大写的单词。如果可选的第二个参数sep不存在或为None,则空白字符的运行将被单个空格替换,并且前导和尾部的空白将被删除,否则sep用于分隔和连接单词。
这里总结了不同的方法,以及一些需要注意的陷阱
它们将适用于所有这些输入:
"" => ""
"a b c" => "A B C"
"foO baR" => "FoO BaR"
"foo bar" => "Foo Bar"
"foo's bar" => "Foo's Bar"
"foo's1bar" => "Foo's1bar"
"foo 1bar" => "Foo 1bar"
Splitting the sentence into words and capitalizing the first letter then join it back together: # Be careful with multiple spaces, and empty strings # for empty words w[0] would cause an index error, # but with w[:1] we get an empty string as desired def cap_sentence(s): return ' '.join(w[:1].upper() + w[1:] for w in s.split(' ')) Without splitting the string, checking blank spaces to find the start of a word def cap_sentence(s): return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) ) Or using generators: # Iterate through each of the characters in the string # and capitalize the first char and any char after a blank space from itertools import chain def cap_sentence(s): return ''.join( (c.upper() if prev == ' ' else c) for c, prev in zip(s, chain(' ', s)) ) Using regular expressions, from steveha's answer: # match the beginning of the string or a space, followed by a non-space import re def cap_sentence(s): return re.sub("(^|\s)(\S)", lambda m: m.group(1) + m.group(2).upper(), s)
现在,这些是其他一些被发布的答案,如果我们将一个单词定义为句子的开头或空格后的任何东西,输入就不会像预期的那样工作:
.title () 返回s.title () #不需要的输出: "foO baR" => "foO baR" "foo's bar" => "foo's bar" "foo's1bar" => "foo's1bar" "foo 1bar" => "foo 1bar"
.capitalize()或.capwords() 返回' '.join(w.r esize () for s.split()中的w) #或 进口的字符串 返回string.capwords(年代) #不需要的输出: "foO baR" => "foO baR" "foo bar" => "foo bar" 使用' '作为分割将修复第二个输出,但不能修复第一个输出 返回' '.join(w.r esize () for w in s.s split(' ')) #或 进口的字符串 返回字符串。大写字符(s, ' ') #不需要的输出: "foO baR" => "foO baR"
.upper () 注意使用多个空格,这可以通过使用' '进行分割来修复(如答案顶部所示) 返回' ' . join (w [0] .upper () + w (1:) w s.split ()) #不需要的输出: "foo bar" => "foo bar"