How to capitalize the first letter of each word in a string (Python)?
1 | s = 'the brown fox' |
…在这里做点什么…
1 | 'The Brown Fox' |
最简单的方法是什么?
字符串的
1 2 3 4 | >>>"hello world".title() 'Hello World' >>> u"hello world".title() u'Hello World' |
但是,要注意嵌入了撇号的字符串,如文档中所述。
The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:
1
2 >>>"they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
1 2 | >>>"they're bill's friends from the UK".title() "They'Re Bill'S Friends From The Uk" |
试试
1 2 3 | import string string.capwords("they're bill's friends from the UK") >>>"They're Bill's Friends From The Uk" |
来自capwords上的python文档:
Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.
就因为这类事情对我来说很有趣,这里还有两个解决方案。
拆分为单词,在每个单词的开头加上大写,然后重新加入。这将改变将单词分隔成单个空白的空白,不管它是什么。
1 2 3 | s = 'the brown fox' lst = [word[0].upper() + word[1:] for word in s.split()] s ="".join(lst) |
编辑:我不记得写上述代码时我在想什么,但是不需要构建一个显式列表;我们可以使用生成器表达式以懒惰的方式来完成它。所以这里有一个更好的解决方案:
1 2 | s = 'the brown fox' s = ' '.join(word[0].upper() + word[1:] for word in s.split()) |
使用正则表达式匹配字符串的开头,或者空格分隔词,再加上一个非空白字符;使用括号标记"匹配组"。编写一个获取匹配对象的函数,并返回空白匹配组未更改和大写非空白字符匹配组。然后使用
1 2 3 4 5 6 7 8 9 10 11 12 | 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" |
我很高兴我研究了这个答案。我不知道
@jibberia anwser的复制粘贴就绪版本:
1 2 | def capitalize(line): return ' '.join(s[:1].upper() + s[1:] for s in line.split(' ')) |
下面是不同方法的总结,它们将适用于所有这些输入:
1 2 3 4 5 6 7 | "" =>"" "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" |
-最简单的解决方案是将句子拆分为单词,并将第一个字母大写,然后将其重新连接在一起:
1 2 3 4 5 | # 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(' ')) |
-如果不想先将输入字符串拆分为单词,然后使用花哨的生成器:
1 2 3 4 5 | # 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:
1 2 | def cap_sentence(s): return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) ) |
-或者您可以使用正则表达式,从Steveha的答案中:
1 2 3 4 | # 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) |
现在,这些是一些其他已发布的答案,如果我们使用单词的定义作为句子开头或空格后的任何内容,则这些答案和输入无法按预期工作:
1 2 3 4 5 6 7 | return s.title() # Undesired outputs: "foO baR" =>"Foo Bar" "foo's bar" =>"Foo'S Bar" "foo's1bar" =>"Foo'S1Bar" "foo 1bar" =>"Foo 1Bar" |
1 2 3 4 5 6 7 8 | return ' '.join(w.capitalize() for w in s.split()) # or import string return string.capwords(s) # Undesired outputs: "foO baR" =>"Foo Bar" "foo bar" =>"Foo Bar" |
将""用于拆分将修复第二个输出,但capwords()仍然无法用于第一个输出。
1 2 3 4 5 6 7 | return ' '.join(w.capitalize() for w in s.split(' ')) # or import string return string.capwords(s, ' ') # Undesired outputs: "foO baR" =>"Foo Bar" |
注意多个空格
1 2 3 | return ' '.join(w[0].upper() + w[1:] for w in s.split()) # Undesired outputs: "foo bar" =>"Foo Bar" |
当解决方案简单且安全时,为什么要用连接和循环使您的生活复杂化??
只要这样做:
1 2 | string ="the brown fox" string[0].upper()+string[1:] |
如果str.title()不适用于您,请自己进行大小写。
一班轮:
1 2 | >>> ' '.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" |
明显的例子:
1 2 3 4 5 6 7 | 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) |
如果您访问[1:],空字符串将引发错误,因此我将使用:
1 2 3 4 | def my_uppercase(title): if not title: return '' return title[0].upper() + title[1:] |
仅大写第一个字母。
正如马克指出的,你应该使用
1 | "MyAwesomeString".title() |
但是,如果要在django模板内将第一个字母变为大写,可以使用以下方法:
1 | {{"MyAwesomeString"|title }} |
或使用变量:
1 | {{ myvar|title }} |
建议的方法str.title()并非在所有情况下都有效。例如:
1 2 3 | string ="a b 3c" string.title() >"A B 3C" |
而不是
我认为,最好这样做:
1 2 3 4 5 6 | 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' |
将单词大写…
1 2 | str ="this is string example.... wow!!!"; print"str.title() :", str.title(); |
@Gary02127注释,位于解决方案标题下方,带撇号
1 2 3 4 5 6 7 | 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)) |
如果你只想要第一个字母:"你好,世界"。大写())输出:你好世界
但要将每个单词大写:"你好,世界"。标题())输出:你好世界
不要忽视空白的保存。如果你想处理
1 2 | def propercase(s): return ''.join(map(''.capitalize, re.split(r'(\s+)', s))) |
**如果您想缩小尺寸**
1 2 3 4 5 6 7 | #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 |
我很喜欢这个答案:
@jibberia anwser的复制粘贴就绪版本:
1 2 | def capitalize(line): return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')]) |
但是,我发送的一些行拆分了一些空白的""字符,这些字符在尝试执行s[1:]时会导致错误。可能有更好的方法可以做到这一点,但我必须添加一个if len(s)>0,如
1 | return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0]) |