首页 文章

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

提问于
浏览
451
s = 'the brown fox'

......在这做点什么......

s 应该是:

'The Brown Fox'

最简单的方法是什么?

15 回答

  • 765

    建议的方法str.title()在所有情况下都不起作用 . 例如:

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

    而不是 "A B 3c" .

    我认为,做这样的事情会更好:

    def capitalize_words(string):
        words = string.split()
        return ' '.join([word.capitalize() for word in words])
    
    capitalize_words(string)
    >'A B 3c'
    
  • 87

    大写单词......

    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))
    
  • 1

    .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 docs on capwords

    使用str.split()将参数拆分为单词,使用str.capitalize()对每个单词进行大写,并使用str.join()连接大写单词 . 如果可选的第二个参数sep不存在或者None,则用空格字符替换单个空格并删除前导和尾随空格,否则使用sep来拆分和连接单词 .

  • 10

    Here's a summary of different ways to do it:

    最简单的解决方案是将句子分成单词并将第一个字母大写,然后将其连接在一起 .

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

    或者您可以使用正则表达式,来自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)
    

    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 和输入不能正常工作的输入:

    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"
    

    使用''进行拆分将修复第二个输出,但是capwords()仍然无法用于第一个输出

    return ' '.join(w.capitalize() for w in s.split(' '))    
      # or
      import string
      return string.capwords(s, ' ')
    
    # Undesired outputs:
    "foO baR"    => "Foo Bar"
    

    小心多个空格

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

    如果访问[1:],空字符串将引发错误,因此我会使用:

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

    仅限大写第一个字母 .

  • 3

    仅仅因为这种事情对我来说很有趣,这里还有两个解决方案 .

    分成单词,从分组中初始化每个单词,然后重新加入 . 这将改变将单词分隔成单个空白区域的空白区域,无论它是什么 .

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

    编辑:当我编写上面的代码时,我不记得我在想什么,但是没有必要 Build 一个明确的列表;我们可以使用生成器表达式以懒惰的方式执行它 . 所以这是一个更好的解决方案:

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

    使用正则表达式匹配字符串的开头,或分隔单词的空格,以及单个非空白字符;用括号标记"match groups" . 编写一个带有匹配对象的函数,并返回未更改的空格匹配组和以大写形式返回的非空白字符匹配组 . 然后使用 re.sub() 替换模式 . 这个没有第一个解决方案的标点符号问题,也不像我的第一个解决方案那样重做白色空间 . 这个产生最好的结果 .

    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() 内进行非平凡处理以产生最终结果!

  • 14

    当解决方案简单安全时,为什么会使用连接和循环使你的生活变得复杂?

    这样做:

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

    正如马克指出你应该使用.title()

    "MyAwesomeString".title()
    

    但是,如果想将第一个字母设为大写 inside a django template ,则可以使用:

    {{ "MyAwesomeString"|title }}
    

    或使用变量:

    {{ myvar|title }}
    
  • 12

    我真的很喜欢这个答案:

    @jibberia anwser的复制粘贴就绪版本:

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

    但是我发送的一些行分离了一些空白的''字符,这些字符在尝试执行s [1:]时会导致错误 . 可能有更好的方法来做到这一点,但我不得不添加if len(s)> 0,如

    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 propercase(s):
        return ''.join(map(''.capitalize, re.split(r'(\s+)', s)))
    
  • 2

    字符串的.title()方法(ASCII或Unicode很好)执行此操作:

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

    但是,请注意带有嵌入式撇号的字符串,如文档中所述 .

    该算法使用简单的与语言无关的单词定义作为连续字母组 . 该定义在许多情况下起作用,但它意味着收缩和占有的撇号形成单词边界,这可能不是理想的结果:>>>“他们是来自英国的账单的朋友”.title()
    “他们是比尔的英国朋友”

  • 5

    @jibberia anwser的复制粘贴就绪版本:

    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)
    

相关问题