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

前端 未结 19 2034
深忆病人
深忆病人 2020-11-22 17:17
s = \'the brown fox\'

...do something here...

s should be:

\'The Brown Fox\'

What\'s the easiest

相关标签:
19条回答
  • 2020-11-22 17:28

    An empty string will raise an error if you access [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.

    0 讨论(0)
  • 2020-11-22 17:28

    The suggested method str.title() does not work in all cases. For example:

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

    instead of "A B 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'
    
    0 讨论(0)
  • 2020-11-22 17:30

    The .title() method of a string (either ASCII or Unicode is fine) does this:

    >>> "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"
    
    0 讨论(0)
  • 2020-11-22 17:33

    If str.title() doesn't work for you, do the capitalization yourself.

    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)
    
    0 讨论(0)
  • 2020-11-22 17:35

    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
    
    0 讨论(0)
  • 2020-11-22 17:36

    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. 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! You can do nontrivial processing inside re.sub() to produce the final result!

    0 讨论(0)
提交回复
热议问题