Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将字符串中每个单词的第一个字母大写?_Python_Capitalization_Capitalize - Fatal编程技术网

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

Python 如何将字符串中每个单词的第一个字母大写?,python,capitalization,capitalize,Python,Capitalization,Capitalize,…在这里做点什么 s应为: s = 'the brown fox' 最简单的方法是什么?字符串方法(ASCII或Unicode都可以)执行以下操作: 'The Brown Fox' 但是,请注意文档中提到的带有内嵌撇号的字符串 该算法使用一个简单的独立于语言的定义,将一个单词定义为一组连续的字母。这个定义在许多语境中都适用,但它意味着缩略语和所有格中的撇号形成了单词边界,这可能不是期望的结果: >>> "hello world".title() 'Hel

…在这里做点什么

s
应为:

s = 'the brown fox'
最简单的方法是什么?

字符串方法(ASCII或Unicode都可以)执行以下操作:

'The Brown Fox'
但是,请注意文档中提到的带有内嵌撇号的字符串

该算法使用一个简单的独立于语言的定义,将一个单词定义为一组连续的字母。这个定义在许多语境中都适用,但它意味着缩略语和所有格中的撇号形成了单词边界,这可能不是期望的结果:

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

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

拆分为单词,在拆分的组中为每个单词加上大写字母,然后重新加入。这将改变将单词分隔为单个空格的空白,无论它是什么

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

编辑:我不记得我写上述代码时的想法,但是没有必要建立一个明确的列表;我们可以使用生成器表达式以惰性方式执行此操作。因此,这里有一个更好的解决方案:

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

使用正则表达式匹配字符串的开头,或空格分隔单词,再加上一个非空格字符;使用括号标记“匹配组”。编写一个函数,该函数接受匹配对象,并以大写形式返回空白匹配组和非空白字符匹配组。然后使用
re.sub()
替换模式。这一个没有第一个解决方案的标点问题,也没有像我的第一个解决方案那样重做空白。这个效果最好

s = 'the brown fox'
s = ' '.join(word[0].upper() + word[1:] for word in s.split())
我很高兴我研究了这个答案。我不知道
re.sub()
可以使用函数!您可以在
re.sub()
中执行非平凡的处理来生成最终结果

如果str.title()对您不起作用,请自己进行大写

  • 将字符串拆分为单词列表
  • 将每个单词的第一个字母大写
  • 把单词连成一个字符串
  • 一艘班轮:

    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"
    
    明确的例子:

    >>> ' '.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"
    
    string = "the brown fox"
    string[0].upper()+string[1:]
    

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

    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)
    
    import string
    string.capwords("they're bill's friends from the UK")
    >>>"They're Bill's Friends From The Uk"
    
    这种方法不能很好地工作

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

    从:

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


    我很喜欢这个答案:


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

    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)
    
    import string
    string.capwords("they're bill's friends from the UK")
    >>>"They're Bill's Friends From The Uk"
    
    但是我发送的一些行拆分了一些空白的“”字符,这些字符在尝试执行s[1:]时会导致错误。可能有更好的方法来实现这一点,但我必须添加if len(s)>0,如中所示

    要大写单词

    return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])
    
    @Gary02127注释,下面的解决方案使用带撇号的标题

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

    正如Mark指出的,您应该使用:

    但是,如果您希望在Django模板中使用大写字母,可以使用以下方法:

    "MyAwesomeString".title()
    
    string = 1 w 2 r 3g
    
    或使用变量:

    {{ "MyAwesomeString"|title }}
    

    当解决方案简单且安全时,为什么要用连接和for循环使生活复杂化

    只要这样做:

    {{ myvar|title }}
    

    建议的方法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"
    
    string = "the brown fox"
    string[0].upper()+string[1:]
    
    而不是
    “ab3c”

    我认为,最好是这样做:

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

    这里总结了各种方法,它们适用于所有这些输入:

    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'
    
    -最简单的解决方案是将句子拆分为单词,并将第一个字母大写,然后将其重新连接在一起:

    ""           => ""       
    "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"     
    
    -如果不想先将输入字符串拆分为单词,并使用奇特的生成器:

    # 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(' ')) 
    
    -或者不导入itertools:

    # 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)) )
    
    -也可以使用正则表达式,从:


    现在,这些是一些已发布的其他答案,以及如果我们使用单词的定义作为句子的开头或空格后的任何内容,则这些答案和输入不符合预期:

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

    将“”用于拆分将修复第二个输出,但capwords()对于第一个输出仍然不起作用

      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"      
    

    注意多个空格

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

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

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

    仅大写第一个字母。

    不要忽略保留空白。如果您想处理
    'fred flinstone'
    而得到的是
    'fred flinstone'
    而不是
    'fred flinstone'
    ,那么您已经破坏了您的空白区域。上面的一些解决方案将丢失空白。这里有一个适合Python2和Python3的解决方案,它保留了空白

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

    如果你想要第一个字母:

    “你好,世界”。大写() “你好,世界” 但要大写每个单词:

    >“你好,世界”。title()
    “你好,世界”
    
    如果您想缩小尺寸
    虽然所有的答案都是令人满意的,但我会尽量把这两个额外的案例和之前的案例都包括在内

    如果空间不一致,并且您希望保持不变

    如果所有字符串不是从字母表开始的

    在这里,您可以使用:

    "MyAwesomeString".title()
    
    string = 1 w 2 r 3g
    
    这将为您提供:

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

    一个适用于Python 3的快速函数

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

    使用非均匀空格将字符串大写

    我想在@Amit Gupta的非均匀空间点上添加以下内容:

    从原来的问题开始,我们想将字符串
    s='thebrownfox'
    中的每个单词大写。如果字符串是
    s='thebrownfox'
    ,带有非均匀空格,该怎么办

    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.
    

    对于您的问题,最简单的解决方案在我的案例中有效:

    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)
    
    .title()方法不适用于所有测试用例,因此将.capitalize()、.replace()和.split()一起使用是将每个wo的第一个字母大写的最佳选择
    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.
    
    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)
    
    import string
    def solve(s):
        return string.capwords(s,' ') 
        
    s=input()
    res=solve(s)
    print(res)
    
         k=y.split()
         for i in k:
            y=y.replace(i,i.capitalize())
         return y