简体   繁体   English

如何将字符串中每个单词的首字母大写?

[英]How can I capitalize the first letter of each word in a string?

s = 'the brown fox'

...do something here... ...在这里做点什么...

s should be:应该s

'The Brown Fox'

What's the easiest way to do this?最简单的方法是什么?

The .title() method of a string (either ASCII or Unicode is fine) does this:字符串的.title()方法(ASCII 或 Unicode 都可以)执行以下操作:

>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'

However, look out for strings with embedded apostrophes, as noted in the docs.但是,请注意带有嵌入撇号的字符串,如文档中所述。

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:该定义在许多情况下都适用,但这意味着收缩和所有格中的撇号形成单词边界,这可能不是预期的结果:

 >>> "they're bill's friends from the UK".title() "They'Re Bill'S Friends From The Uk"

The.title() method can't work well, .title()方法不能很好地工作,

>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

Try string.capwords() method,尝试string.capwords()方法,

import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"

From the Python documentation on capwords :来自 关于 capwordsPython 文档

Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join().使用 str.split() 将参数拆分为单词,使用 str.capitalize() 将每个单词大写,并使用 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.如果可选的第二个参数 sep 不存在或 None ,空白字符的运行将被单个空格替换并删除前导和尾随空格,否则 sep 用于拆分和连接单词。

Just because this sort of thing is fun for me, here are two more solutions.仅仅因为这种事情对我来说很有趣,这里还有两个解决方案。

Split into words, initial-cap each word from the split groups, and rejoin.拆分成单词,对拆分组中的每个单词进行初始上限,然后重新加入。 This will change the white space separating the words into a single white space, no matter what it was.这会将分隔单词的空白更改为单个空白,无论它是什么。

s = 'the brown fox'
lst = [word[0].upper() + word[1:] for word in s.split()]
s = " ".join(lst)

EDIT: I don't remember what I was thinking back when I wrote the above code, but there is no need to build an explicit list;编辑:我不记得我在写上面的代码时在想什么,但是没有必要建立一个明确的列表; we can use a generator expression to do it in lazy fashion.我们可以使用生成器表达式以懒惰的方式完成它。 So here is a better solution:所以这里有一个更好的解决方案:

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.然后使用re.sub()替换模式。 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"

I'm glad I researched this answer.我很高兴我研究了这个答案。 I had no idea that re.sub() could take a function!我不知道re.sub()可以带一个函数! You can do nontrivial processing inside re.sub() to produce the final result!您可以在re.sub()进行非平凡处理以产生最终结果!

Here's a summary of different ways to do it, they 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"     

- The simplest solution is to split the sentence into words and capitalize 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(' ')) 

- If you don't want to split the input string into words first, and using fancy 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)) )

- Or without importing itertools: - 或者不导入 itertools:

def cap_sentence(s):
  return ''.join( (c.upper() if i == 0 or s[i-1] == ' ' else c) for i, c in enumerate(s) )

- Or you can use regular expressions, from steveha's answer : - 或者您可以使用正则表达式,来自steveha 的回答

# 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)

Now, these are some other answers that were posted, and inputs for which they don't work as expected if we are using the definition of a word being the start of the sentence or anything after a blank space:现在,这些是发布的其他一些答案,以及如果我们使用单词的定义作为句子的开头或空格之后的任何内容,它们将无法按预期工作的输入:

  return s.title()

# Undesired outputs: 
"foO baR"    => "Foo Bar"       
"foo's bar"  => "Foo'S Bar" 
"foo's1bar"  => "Foo'S1Bar"     
"foo 1bar"   => "Foo 1Bar"      

  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"      

using ' ' for the split will fix the second output, but capwords() still won't work for the first使用 ' ' 进行拆分将修复第二个输出,但 capwords() 仍然不适用于第一个

  return ' '.join(w.capitalize() for w in s.split(' '))    
  # or
  import string
  return string.capwords(s, ' ')

# Undesired outputs:
"foO baR"    => "Foo Bar"      

Be careful with multiple blank spaces小心多个空格

  return ' '.join(w[0].upper() + w[1:] for w in s.split())
# Undesired outputs:
"foo    bar" => "Foo Bar"                 

Copy-paste-ready version of @jibberia anwser: @jibberia anwser 的复制粘贴就绪版本:

def capitalize(line):
    return ' '.join(s[:1].upper() + s[1:] for s in line.split(' '))

Why do you complicate your life with joins and for loops when the solution is simple and safe??当解决方案既简单又安全时,为什么要使用连接和 for 循环使您的生活复杂化?

Just do this:只需这样做:

string = "the brown fox"
string[0].upper()+string[1:]

If str.title() doesn't work for you, do the capitalization yourself.如果 str.title() 对您不起作用,请自己进行大写。

  1. Split the string into a list of words将字符串拆分为单词列表
  2. Capitalize the first letter of each word每个单词的首字母大写
  3. Join the words into a single string将单词连接成一个字符串

One-liner:单线:

>>> ' '.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"

Clear example:清晰的例子:

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)

If only you want the first letter:如果你只想要第一个字母:

>>> 'hello world'.capitalize()
'Hello world'

But to capitalize each word:但是要大写每个单词:

>>> 'hello world'.title()
'Hello World'

An empty string will raise an error if you access [1:].如果您访问 [1:],空字符串将引发错误。 Therefore I would use:因此我会使用:

def my_uppercase(title):
    if not title:
       return ''
    return title[0].upper() + title[1:]

to uppercase the first letter only.只大写第一个字母。

Although all the answers are already satisfactory, I'll try to cover the two extra cases along with the all the previous case.尽管所有的答案都已经令人满意,但我将尝试将两个额外的案例与之前的所有案例一起讨论。

if the spaces are not uniform and you want to maintain the same如果空间不均匀并且您想保持相同

string = hello    world i  am    here.

if all the string are not starting from alphabets如果所有字符串都不是从字母开始

string = 1 w 2 r 3g

Here you can use this:在这里你可以使用这个:

def solve(s):
    a = s.split(' ')
    for i in range(len(a)):
        a[i]= a[i].capitalize()
    return ' '.join(a)

This will give you:这会给你:

output = Hello    World I  Am    Here
output = 1 W 2 R 3g

The suggested method str.title() does not work in all cases.建议的方法 str.title() 不适用于所有情况。 For example:例如:

string = "a b 3c"
string.title()
> "A B 3C"

instead of "AB 3c" .而不是"AB 3c"

I think, it is better to do something like this:我认为,最好做这样的事情:

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'

As Mark pointed out, you should use .title() :正如马克指出的那样,你应该使用.title()

"MyAwesomeString".title()

However, if would like to make the first letter uppercase inside a Django template , you could use this:但是,如果想让Django 模板中的第一个字母大写,您可以使用:

{{ "MyAwesomeString"|title }}

Or using a variable:或者使用变量:

{{ myvar|title }}

To capitalize words...将单词大写...

str = "this is string example....  wow!!!";
print "str.title() : ", str.title();

@Gary02127 comment, the below solution works with title with apostrophe @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))

Don't overlook the preservation of white space.不要忽视留白。 If you want to process 'fred flinstone' and you get 'Fred Flinstone' instead of 'Fred Flinstone' , you've corrupted your white space.如果您想处理'fred flinstone'并且您得到'Fred Flinstone'而不是'Fred Flinstone' ,那么您已经破坏了您的空白区域。 Some of the above solutions will lose white space.上述一些解决方案会丢失空白。 Here's a solution that's good for Python 2 and 3 and preserves white space.这是一个适用于 Python 2 和 3 并保留空白的解决方案。

def propercase(s):
    return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))

A quick function worked for Python 3一个适用于 Python 3 的快速函数

Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> capitalizeFirtChar = lambda s: s[:1].upper() + s[1:]
>>> print(capitalizeFirtChar('помните своих Предковъ. Сражайся за Правду и Справедливость!'))
Помните своих Предковъ. Сражайся за Правду и Справедливость!
>>> print(capitalizeFirtChar('хай живе вільна Україна! Хай живе Любовь поміж нас.'))
Хай живе вільна Україна! Хай живе Любовь поміж нас.
>>> print(capitalizeFirtChar('faith and Labour make Dreams come true.'))
Faith and Labour make Dreams come true.

Capitalize string with non-uniform spaces用非均匀空格将字符串大写

I would like to add to @Amit Gupta's point of non-uniform spaces:我想补充@Amit Gupta 的非均匀空间点:

From the original question, we would like to capitalize every word in the string s = 'the brown fox' .根据最初的问题,我们希望将字符串s = 'the brown fox'中的每个单词都大写。 What if the string was s = 'the brown fox' with non-uniform spaces.如果字符串是带有非均匀空格的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)

The .title() method won't work in all test cases, so using .capitalize(), .replace() and .split() together is the best choice to capitalize the first letter of each word. .title() 方法不适用于所有测试用例,因此将 .capitalize()、.replace() 和 .split() 一起使用是将每个单词的首字母大写的最佳选择。

eg: def caps(y):例如:def caps(y):

     k=y.split()
     for i in k:
        y=y.replace(i,i.capitalize())
     return y

You can try this.你可以试试这个。 simple and neat.简单而整洁。

def cap_each(string):
    list_of_words = string.split(" ")

    for word in list_of_words:
        list_of_words[list_of_words.index(word)] = word.capitalize()

    return " ".join(list_of_words)

Another oneline solution could be:另一个在线解决方案可能是:

" ".join(map(lambda d: d.capitalize(), word.split(' ')))

You can use title() method to capitalize each word in a string in Python:您可以使用title()方法将 Python 中字符串中的每个单词大写:

string = "this is a test string"
capitalized_string = string.title()
print(capitalized_string)

Output: Output:

This Is A Test String

In case you want to downsize如果您想缩小尺寸

# 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

Easiest solution for your question, it worked in my case:您的问题最简单的解决方案,它适用于我的情况:

import string
def solve(s):
    return string.capwords(s,' ') 
    
s=input()
res=solve(s)
print(res)

I really like this answer:我真的很喜欢这个答案:

Copy-paste-ready version of @jibberia anwser: @jibberia anwser 的复制粘贴就绪版本:

def capitalize(line):
    return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])

But some of the lines that I was sending split off some blank '' characters that caused errors when trying to do s[1:].但是我发送的一些行拆分了一些空白的 '' 字符,这些字符在尝试执行 s[1:] 时会导致错误。 There is probably a better way to do this, but I had to add in a if len(s)>0, as in可能有更好的方法来做到这一点,但我必须添加一个 if len(s)>0,如

return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 python 中每个单词的首字母大写? - How to capitalize the First letter of each word in python? 如何反转字符串中的每个单词,并且python中每个单词的第一个字母大写? - How to reverse each word in string and first letter is capitalize of each word in python? Hackerrank Python 挑战:将 Python 中字符串中每个单词的首字母大写 - Hackerrank Python Challenge: Capitalize The First letter of each word in a String in Python Python - 仅将字符串中每个单词的第一个字母大写 - Python - Capitalize only first letter of each word in a string 如何将字符串中每个单词的第一个字符大写? - How to capitalize first character of each word in a string? 将Python中的每个单词的首字母大写 - Capitalize first letter of each word in the column Python 如何将 Python 字符串中每个单词的第一个和最后一个字母大写? - How to capitalize first and last letters of each word in a Python string? 如何在 Python 中将字符串的第一个字母大写,而忽略 HTML 标签? - How can I capitalize the first letter of a string in Python, ignoring HTML tags? 将[和]之间的每个单词的首字母大写在文本文件中 - Capitalize first letter of each word between [ and ] in text file 如何让我的代码将其中包含大写字母的单词的首字母大写? (猪拉丁语) - How do I make my code capitalize the first letter of the word that has a capital letter in it? (Pig Latin)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM