Python capitalize each word in string

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!

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    Given the string, the task is to capitalize the first and last character of each word in a string. 

    Examples:

    Input: hello world 
    Output: HellO WorlD
    
    Input: welcome to geeksforgeeks
    Output: WelcomE TO GeeksforgeekS

    Approach:1

    • Access the last element using indexing.
    • Capitalize the first word using title() method.
    • Then join the each word using join() method.
    • Perform all the operations inside lambda for writing the code in one-line.

    Below is the implementation. 

    Python3

    def word_both_cap(str):

        return ' '.join(map(lambda s: s[:-1]+s[-1].upper(),

                            s.title().split()))

    s = "welcome to geeksforgeeks"

    print("String before:", s)

    print("String after:", word_both_cap(str))

    Output:

    String before: welcome to geeksforgeeks
    String after: WelcomE TO GeeksforgeekS

    ->There used a built-in function map( ) in place of that also we can use filter( ).Basically these are the functions which take a list or any other function and give result on it.

    Time Complexity: O(n)

    Auxiliary Space: O(n), where n is number of characters in string.

    Approach: 2: Using slicing and upper(),split() methods

    Python3

    s = "welcome to geeksforgeeks"

    print("String before:", s)

    a = s.split()

    res = []

    for i in a:

        x = i[0].upper()+i[1:-1]+i[-1].upper()

        res.append(x)

    res = " ".join(res)

    print("String after:", res)

    Output

    String before: welcome to geeksforgeeks
    String after: WelcomE TO GeeksforgeekS

    Time Complexity: O(n)

    Auxiliary Space: O(n)

    Like Article

    Save Article

    Python capitalize each word: A sequence of characters is referred to as a string.

    Characters are not used by computers instead, numbers are used (binary). Characters appear on your computer, but they are internally stored and manipulated as a sequence of 0s and 1s.

    In Python, a string is a set of Unicode characters. Unicode was designed to include every character in every language and to introduce encoding uniformity to the world. Python Unicode will tell you all about Unicode you need to know.

    • Python String – Replace() Method
    • Python Program to Accept a Sentence and Print only the First Letter of Each Word in Capital Letters Separated by a Full Stop
    • Python Program to Capitalize the First Letter of Every Word in the File

    Example:

    Input:

    string = "this is btech geeks"

    Output:

    This Is Btech Geeks

    Given a string, the task is to convert each word first letter to uppercase

    Python capitalize first letter: There are several ways to capitalize the first letter of each word in a string some of them are:

    • Using capitalize() function
    • Using title() function
    • Using string.capwords() function
    • Using Regex

    Method #1:Using capitalize() function

    Syntax: given_string.capitalize()
    Parameters: No parameters will be passed
    Return : Each word’s first letter is capitalised in the string.

    Approach:

    • Because spaces separate all of the words in a sentence.
    • We must use split to divide the sentence into spaces ().
    • We separated all of the words with spaces and saved them in a list.
    • Using the for loop, traverse the wordslist and use the capitalise feature to convert each word to its first letter capital.
    • Using the join function, convert the wordslist to a string.
    • Print the string.

    Below is the implementation of above approach:

    # given string
    string = "this is btech geeks"
    # convert the string to list and split it
    wordslist = list(string.split())
    # Traverse the words list and capitalize each word in list
    for i in range(len(wordslist)):
      # capitizing the word
        wordslist[i] = wordslist[i].capitalize()
    # converting string to list using join() function
    finalstring = ' '.join(wordslist)
    # printing the final string
    print(finalstring)
    

    Output:

    This Is Btech Geeks

    Method #2:Using title() function

    Before returning a new string, the title() function in Python converts the first character in each word to Uppercase and the remaining characters in the string to Lowercase.

    • Syntax: string_name.title()
    • Parameters: string in which the first character of each word must be converted to uppercase
    • Return Value: Each word’s first letter is capitalised in the string.

    Below is the implementation:

    # given string
    string = "this is btech geeks"
    # using title() to convert all words first letter to capital
    finalstring = string.title()
    # print the final string
    print(finalstring)

    Output:

    This Is Btech Geeks

    Method #3:Using string.capwords() function

    Using the spilt() method in Python, the string capwords() method capitalises all of the words in the string.

    • Syntax: string.capwords(given_string)
    • Parameters: The givenstring that needs formatting.
    • Return Value: Each word’s first letter is capitalised in the string.

    Break the statement into words, capitalise each word with capitalise, and then join the capitalised words together with join. If the optional second argument sep is None or missing, whitespace characters are replaced with a single space and leading and trailing whitespace is removed.

    Below is the implementation:

    # importing string
    import string
    # given string
    givenstring = "this is btech geeks"
    # using string.capwords() to convert all words first letter to capital
    finalstring = string.capwords(givenstring)
    # print the final string
    print(finalstring)
    

    Output:

    This Is Btech Geeks

    Method #4:Using Regex

    We’ll use regex to find the first character of each word and convert it to uppercase.

    Below is the implementation:

    # importing regex
    import re
    
    # function which converts every first letter of each word to capital
    
    def convertFirstwordUpper(string):
        # Convert the group 2 to uppercase and join groups 1 and 2 together. 
        return string.group(1) + string.group(2).upper()
    
    
    # given string
    string = "this is btech geeks"
    
    # using regex
    resultstring = re.sub("(^|s)(S)", convertFirstwordUpper, string)
    # print the final string
    print(resultstring)
    

    Output:

    This Is Btech Geeks

    Related Programs:

    • capitalize first letter of each word in a string in java
    • python program to read a file and capitalize the first letter of every word in the file
    • convert first letter of each word of a string to upper case in cpp
    • how to uppercase the first letter of a string in javascript
    • check the first or last character of a string in python
    • python program to remove the ith occurrence of the given word in a list where words can repeat
    • python program to sort a list of tuples in increasing order by the last element in each tuple

    Python has many built-in methods that perform operations on strings. One of the operations is to change the case of letters. We’ll see different ways to change the case of the letters in a string, and go through many examples in each section, and finally go through some of the applications.

    Python strings are immutable, which means that once created these strings cannot be modified. As a consequence, most of the functions that operate on strings actually return a modified copy of the string; the original string is unchanged.

    Let’s take a look at some of the ways we can manipulate strings to change the case of words.

    Different cases

    We have covered different cases like:

    • Capitalize the first letter using capitalize()
    • Convert the entire string to upper-case
    • Convert the entire string to lower-case
    • Capitalize first letter of each word

    Capitalize the first letter using capitalize()

    To capitalize the first letter, use the capitalize() function. This functions converts the first character to uppercase and converts the remaining characters to lowercase. It doesn’t take any parameters and returns the copy of the modified string.

    Syntax:
    str s.capitalize()

    Example:

    s = "hello openGeNus"
    t = s.capitalize()
    print(t)
    
    'Hello opengenus'
    

    Notice that the function capitalize() returned a modified copy of the original string. This means that our original string s was not modified.
    The first letter ‘h’ was converted to ‘H’. Further an upper-case letter ‘G’ was converted to its lower-case letter ‘g’ and similarly ‘N’ was converted to ‘n’

    Convert the entire string to upper-case

    To convert all the letters of the string to uppercase, we can use the upper() function. The function does not take any parameters and returns the copy of modified string with all letters converted to upper-case.

    Syntax:
    str s.upper()

    Example:

    s = "hello openGeNus"
    t = s.upper()
    print(t)
    
    'HELLO OPENGENUS'
    

    Convert the entire string to lower-case

    To convert all the letters of the string to lowercase, we can use the lower() function. This function does not take any parameters and converts all the letters to lowercase.

    Syntax:
    str s.lower()

    Example:

    s = "hello openGeNus"
    t = s.lower()
    print(t)
    
    'hello opengenus'
    

    Capitalize first letter of each word

    To capitalize the first letter of each word use the title() function. This function does not take any parameters and converts the first letter of each word to uppercase and rest of the letters to lowercase and returns the modified copy of the string.

    Syntax:
    str s.title()

    Example:

    s = "hello openGeNus"
    t = s.title()
    print(t)
    
    'Hello Opengenus'
    

    Notice that while each word was capitalized, the rest of the letters were converted to lowercase.

    Applications

    Now that we know how to perform basic case-manipulation, lets see how can this be useful for us?
    There are many simple applications, we’ll go through some of the basic ones.

    Prompts

    A prompt is a text message that prompts the user to enter some input. For example, a prompt to enter a number.

    A simple prompt could be to allow user to provide a permission by typing the word ‘Yes’. In python «Yes», «yeS» or «YES» are all distinct strings, and we need to be able to accept all variants of those. We can write code to check each of those individually, but the lower() or upper() function provides an easy way.

    Let’s go through some sample code

    in = input("Type 'Yes' to continue or 'No' to abort: ")
    if in.lower() == "yes":
        print("task continued")
        # ... more functions
    else: 
        print("task aborted")
        # user did not type Yes
    

    Here, we checked for input ‘Yes’ and every other input would be considered as a ‘No’. This is sometimes useful, but adding a check for ‘No’ might be required; especially when you want to provide additional messages when user types invalid inputs like a number, instead of ‘Yes’ or ‘No’.

    Searching names

    Usually, to speed up searching process, names are better stored in the same case. This is done only when the changing the case would not cause any problems. The reason why you’d want to do this could be to make searching faster. Searching for someone named Alice as «ALice», «ALICE» or «alice» could be confusing and lead to unnecessary work.

    To overcome this problem, names could be stored in upper-case by using the upper() or in lowercase using the lower() function. This would allow for faster searches because now you don’t have to convert all the names while you perform searches which can be time consuming if there are many names or if the search is occurring multiple times. This is usually done in a students list of names, where case of the names would not matter.

    E-mail addresses

    E-mail addresses are not case-sensitive. So in an application that requires sign in, you have to be able to handle all types of email address inputs.

    Email addresses like «example@example.com», «Example@example.com» or «EXAMPLE@example.com» are all same email addresses, but different python strings. Thus the input needs to be converted to lower-case, which is common format for email addresses.

    Here, the lower() function would be useful.

    uname = input("Enter your email id: ")
    temp = uname.lower()
    if search(temp):           # search() defined elsewhere
        passwd = input("Enter your password: ")
    else:
        print("account not found")
    

    here, we have assumed that there is a function search() that searches for temp and returns a boolean value depending on whether or not the email was found.

    In this tutorial, we will look at how to capitalize the first letter of each word in a Python string with the help of some examples.

    capitalize first letter of each word in string

    There are a number of ways to capitalize the first letter of each word in a string in Python. Let’s look at some with the help of examples.

    1. Using string split(), upper(), and join() funtions

    You can use a combination of the string split(), upper() and join() functions to capitalize the first letter of each word in a string. Use the following steps –

    1. Split the string into its constituent words using the string split() function. This function splits the string at the occurrence of whitespace characters in the string by default.
    2. For each word, capitalize the first letter using the string upper() function.
    3. Join the capitalized words back together using the string join() function to get the desired string.

    Let’s look at an example –

    # create a string
    s = "the cat and the dog"
    # capitalize first letter of each word
    new_s = " ".join(word[0].upper()+word[1:] for word in s.split(" "))
    print(new_s)

    Output:

    The Cat And The Dog

    You can see that each word in the resulting string starts with a capital letter.

    This method is straightforward and does not mess with the capitalization of the other characters in the string.

    2. Using string title() function to capitalize first letter of each word

    You can also use the string title() function. Let’s look at an example –

    # create a string
    s = "the cat and the dog"
    # capitalize first letter of each word
    new_s = s.title()
    print(new_s)

    Output:

    The Cat And The Dog

    The resulting string has the first letter of each word in uppercase.

    Note that this function may not give correct results if there are characters such as apostrophes or other uppercase characters present in the string. Here’s an example –

    # create a string
    s = "he's from the USA"
    # capitalize first letter of each word
    new_s = s.title()
    print(new_s)

    Output:

    He'S From The Usa

    You can see that the character just after the apostrophe is also capitalized. Also, note that the case of existing uppercase characters that were not the first character in the word has been altered (“USA” is “Usa”) in the resulting string.

    For more on the string title() function, refer to its documentation.

    3. Using string.capwords() function

    The string.capwords() function can also help you to capitalize the first letter of each word in a string.

    import string
    # create a string
    s = "the cat and the dog"
    # capitalize first letter of each word
    new_s = string.capwords(s)
    print(new_s)

    Output:

    The Cat And The Dog

    The resulting string has the first letter of each word in uppercase.

    Note that this function may not give correct results if there are existing uppercase characters present in the string. Let’s look at an example –

    import string
    # create a string
    s = "he's from the USA"
    # capitalize first letter of each word
    new_s = string.capwords(s)
    print(new_s)

    Output:

    He's From The Usa

    Here, we were able to mitigate the capitalization of the character just after the apostrophe but the case of some uppercase characters was again altered (“USA” is “Usa” in the resulting string).

    For more on the string.capwords() function, refer to its documentation.

    If we use the first method, using string split(), upper(), and join() functions we get the correct results.

    # create a string
    s = "he's from the USA"
    # capitalize first letter of each word
    new_s = " ".join(word[0].upper()+word[1:] for word in s.split(" "))
    print(new_s)

    Output:

    He's From The USA

    The first method is not only intuitive and straightforward but also gives the expected result when it comes to capitalizing the first letter of each word in a string.

    You might also be interested in –

    • Python String Uppercase – With Examples
    • Python – Frequency of each word in String
    • Piyush Raj

      Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

      View all posts

    Понравилась статья? Поделить с друзьями:
  • Python make excel file
  • Python load from excel
  • Python api for excel
  • Python and word documents
  • Python and microsoft word