# 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(' '))
如果您不想先将输入字符串拆分为单词,并使用花式生成器:
# 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)) )
或者不导入itertools
def cap_sentence(s):
return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) )
# 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)
These will work for all these inputs:
"" => ""
"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"
现在,如果我们使用单词的定义作为句子的开头或空格后面的任何内容,那么这些是已发布的 other answers 和输入不能正常工作的输入:
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"
return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])
0
如果只想要第一个字母:'hello world'.capitalize()输出:Hello world
但要大写每个词:'hello world'.title()输出:Hello world
2
如果你想缩小尺寸
#Assuming you are opening a new file
with open(input_file) as file:
lines = [x for x in reader(file) if x]
#for loop to parse the file by line
for line in lines:
name = [x.strip().lower() for x in line if x]
print(name) #check the result
-2
不要忽视白色空间的保存 . 如果你想处理 'fred flinstone' 并得到 'Fred Flinstone' 而不是 'Fred Flinstone' ,那么've corrupted your white space. Some of the above solutions will lose white space. Here'是一个对Python 2和3有用的解决方案并保留空白区域 .
def capitalize(line):
return ' '.join(s[:1].upper() + s[1:] for s in line.split(' '))
159
如果str.title()不适合您,请自行执行大写操作 .
将字符串拆分为单词列表
将首字母大写每个字
将单词加入单个字符串
一内胆:
>>> ' '.join([s[0].upper() + s[1:] for s in "they're bill's friends from the UK".split(' ')])
"They're Bill's Friends From The UK"
清楚的例子:
input = "they're bill's friends from the UK"
words = input.split(' ')
capitalized_words = []
for word in words:
title_case_word = word[0].upper() + word[1:]
capitalized_words.append(title_case_word)
output = ' '.join(capitalized_words)
15 回答
建议的方法str.title()在所有情况下都不起作用 . 例如:
而不是
"A B 3c"
.我认为,做这样的事情会更好:
大写单词......
@ Gary02127评论,下面是撇号的解决方案工作题目
.title()方法无法正常工作,
试试string.capwords()方法,
来自python docs on capwords:
Here's a summary of different ways to do it:
最简单的解决方案是将句子分成单词并将第一个字母大写,然后将其连接在一起 .
如果您不想先将输入字符串拆分为单词,并使用花式生成器:
或者不导入itertools
或者您可以使用正则表达式,来自steveha's answer
These will work for all these inputs:
现在,如果我们使用单词的定义作为句子的开头或空格后面的任何内容,那么这些是已发布的 other answers 和输入不能正常工作的输入:
使用''进行拆分将修复第二个输出,但是capwords()仍然无法用于第一个输出
小心多个空格
如果访问[1:],空字符串将引发错误,因此我会使用:
仅限大写第一个字母 .
仅仅因为这种事情对我来说很有趣,这里还有两个解决方案 .
分成单词,从分组中初始化每个单词,然后重新加入 . 这将改变将单词分隔成单个空白区域的空白区域,无论它是什么 .
编辑:当我编写上面的代码时,我不记得我在想什么,但是没有必要 Build 一个明确的列表;我们可以使用生成器表达式以懒惰的方式执行它 . 所以这是一个更好的解决方案:
使用正则表达式匹配字符串的开头,或分隔单词的空格,以及单个非空白字符;用括号标记"match groups" . 编写一个带有匹配对象的函数,并返回未更改的空格匹配组和以大写形式返回的非空白字符匹配组 . 然后使用
re.sub()
替换模式 . 这个没有第一个解决方案的标点符号问题,也不像我的第一个解决方案那样重做白色空间 . 这个产生最好的结果 .我很高兴我研究了这个答案 . 我不知道
re.sub()
可以采取功能!您可以在re.sub()
内进行非平凡处理以产生最终结果!当解决方案简单安全时,为什么会使用连接和循环使你的生活变得复杂?
这样做:
正如马克指出你应该使用.title():
但是,如果想将第一个字母设为大写 inside a django template ,则可以使用:
或使用变量:
我真的很喜欢这个答案:
@jibberia anwser的复制粘贴就绪版本:
但是我发送的一些行分离了一些空白的''字符,这些字符在尝试执行s [1:]时会导致错误 . 可能有更好的方法来做到这一点,但我不得不添加if len(s)> 0,如
如果只想要第一个字母:'hello world'.capitalize()输出:Hello world
但要大写每个词:'hello world'.title()输出:Hello world
如果你想缩小尺寸
不要忽视白色空间的保存 . 如果你想处理
'fred flinstone'
并得到'Fred Flinstone'
而不是'Fred Flinstone'
,那么've corrupted your white space. Some of the above solutions will lose white space. Here'是一个对Python 2和3有用的解决方案并保留空白区域 .字符串的.title()方法(ASCII或Unicode很好)执行此操作:
但是,请注意带有嵌入式撇号的字符串,如文档中所述 .
@jibberia anwser的复制粘贴就绪版本:
如果str.title()不适合您,请自行执行大写操作 .
将字符串拆分为单词列表
将首字母大写每个字
将单词加入单个字符串
一内胆:
清楚的例子: