s = 'the brown fox'
...在这里做点什么……
S应为:
'The Brown Fox'
最简单的方法是什么?
s = 'the brown fox'
...在这里做点什么……
S应为:
'The Brown Fox'
最简单的方法是什么?
当前回答
当解决方案简单而安全的时候,为什么你要用连接和for循环来使你的生活复杂化?
只要这样做:
string = "the brown fox"
string[0].upper()+string[1:]
其他回答
另一个解决方案是:
" ".join(map(lambda d: d.capitalize(), word.split(' ')))
字符串的.title()方法(ASCII或Unicode都可以)这样做:
>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'
但是,请注意带有内嵌撇号的字符串,如文档中所述。
该算法使用一个简单的独立于语言的单词定义作为连续的字母组。这个定义在很多情况下都适用,但它意味着缩略词和所有格中的撇号形成了单词边界,这可能不是理想的结果: >>> "他们是比尔来自英国的朋友".title() “他们是比尔的英国朋友”
不要忽视空白的保留。如果你想处理“fred flinstone”,你得到的是“fred flinstone”而不是“fred flinstone”,你已经破坏了你的空白空间。上面的一些解决方案会丢失空白。这里有一个解决方案,适用于Python 2和3,并保留了空白。
def propercase(s):
return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))
使用非均匀空格将字符串大写
我想补充一下@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)
只是因为这类事情对我来说很有趣,这里还有两个解决方案。
拆分为单词,从拆分的组中为每个单词加首字母大写,然后重新连接。这将把分隔单词的空白改为一个单独的空白,不管它是什么。
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()中进行非平凡的处理以产生最终结果!