Python capitalize every word

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

    Python String capitalize() method returns a copy of the original string and converts the first character of the string to a capital (uppercase) letter, while making all other characters in the string lowercase letters.

    Python String capitalize() Method Syntax

    Syntax: string_name.capitalize()

    Parameter:  The capitalize() function does not takes any parameter. 

    Return: The capitalize() function returns a string with the first character in the capital.

    Python String capitalize() Method Example

    Python

    name = "geeks FOR geeks"

    print(name.capitalize())

    Output:

    Geeks for geeks

    Example 1: capitalize() only capitalizes the first letter of a string and lowers all the remaining characters

    Python3

    string = "roses are red"

    print("Original string:", string)

    print("After using capitalzie:", string.capitalize())

    Output:

    Original string: roses are red
    After using capitalzie: Roses are red

    Example 2: Python String capitalize() Method Doesn’t Modify the Original String

    Python String capitalize() Method creates and returns a copy of the original string after modifications.

    Python3

    string = "geeks for geeks"

    string_2 = string.capitalize()

    print("New string after using capitalize():", string_2)

    print("Original string:", string)

    Output:

    New string after using capitalize(): Geeks for geeks
    Original string: geeks for geeks

    Like Article

    Save Article

    remove none from list Python

    In this, we will be solving a problem statement of python capitalize first letter of string. We will be discussing the steps and python methods required to solve this problem.

    Strings in Python are one of the most used data structures. While working with strings, the string can be in uppercase, lowercase, or in any other random format. Hence it is difficult to process any random strings. Therefore, we should convert stings into a fixed format that can be easily processed.

    The easiest method to capitalize first letter of string in python is by using string capitalize() method. The capitalize() method converts the first character of the string in uppercase, and the rest other characters in lowercase.

    Syntax

    str_name.capitalize()

    Parameter – It doesn’t take any parameter

    Return Value – Capitalize method returns the copy of the string which the first letter as capital.

    Python Code:

    str_name = "python"
    print("After using capitalize method -> ",str_name.capitalize())
    str_name1 = "python tutorial"
    print("After using capitalize method -> ",str_name1.capitalize())

    Output:-

    After using capitalize method ->  Python
    After using capitalize method ->  Python tutorial

    Using slicing and upper() method to capitalize first letter in string

    Another way to capitalize first letter in string is by using string slicing and the string upper() method. To know more about string slicing you can read here.

    Steps to follow

    1. Separate the first character and the rest of the characters using string slicing.
    2. Make the first character capital using the string upper() method
    3. Concatenate the first character which is a capital letter now with the rest of the characters.

    Python Code:

    str_name = "python"
    first_letter = str_name[0]
    rest_of_charcters = str_name[1:]
    capitalize_string = str_name[0].upper() + rest_of_charcters
    print("After using capitalize method,", str_name,"becomes ->",capitalize_string)

    Output:-

    After using capitalize method, python becomes -> Python

    Also Read:

    • How to remove special characters from string in 4 Ways
    • 3 Ways to Convert List to Set

    Using title() method to capitalize first letter of every word in string

    The easiest way to capitalize the first letter of every word in a string is by using the python string title() method. The string title() method returns a copy of the string in which the first character of each word of the sentence is upper case.

    Syntax

    str_name.title()

    Parameter – It doesn’t take any parameter

    Return Value – A string, in which the first character of each word is capitalized.

    Python Code:

    str_name = "my programming tutorial"
    print("After using capitalize method -> ",str_name.title())
    str_name1 = "python tutorials"
    print("After using capitalize method -> ",str_name1.title())

    Output:-

    After using capitalize method ->  My Programming Tutorial
    
    After using capitalize method ->  Python Tutorials

    Using string.capwords() method to capitalize first letter of every word in string

    Another way to capitalize the first letter of every word in string python is by using string.capwords() method. In Python, the string capwords() method is used to capitalize all words in a string using the spilt() method.

    The Python String capwords() method splits the string using the string split() method. Capitalize each word of the string using the string capitalize() method and join the capitalized words using the join method.

    Syntax

     string.capwords(str_name, sep=None)

    Parameters

    1. Input string
    2. Separator – The character which is used to split the given string. The default value of the separator is None.

    Return Value – A string, in which the first character of each word is capitalized.

    Python Code:

    import string
    str_name = "my programming tutorial"
    print("After using capitalize method -> ",string.capwords(str_name))
    str_name1 = "python tutorials"
    print("After using capitalize method -> ",string.capwords(str_name1))

    Output:-

    After using capitalize method -> My Programming Tutorial
    After using capitalize method -> Python Tutorials

    Using split, capitalize and join methods to capitalize first letter of string python

    In this method, we will perform the following steps-

    • Split the given string, using the string split() method, which returns the list of words present in the string.
    • Capitalize every word in the list using capitalize method().
    • And at last, concatenate the words using the join method.

    Python Code:

    str_name = "my programming tutorial"
    capitalize_string = ' '.join([word.capitalize() for word in str_name.split()]) 
    print("After Capitalize ->", capitalize_string)

    Output:-

    After Capitalize -> My Programming Tutorial

    Also Read: 4 ways to count occurrences in list Python

    Using Regex to capitalize first letter of every word in string

    In Python Regular Expression or Regex is a special sequence of characters that helps to match or find the other strings. To know more about regex in python you can read here.

    Python Code:

    # importing re module
    import re
    # return uppaercase character of every word. 
    def uppercase_first_character(g):
        return g.group(1) + g.group(2).upper()
    str_name = "my programming tutorial"
    capitalize_string = re.sub("(^|s)(S)", uppercase_first_character, str_name)
    print("After using capitalizing using regex -> ", capitalize_string)

    Output:-

    After using capitalizing using regex -> My Programming Tutorial

    How to capitalize every word in list

    To capitalize every word in the list, we can use list comprehension. Use for loop to access each word in the list and then use the string title() method to capitalize the word. To know more about list comprehension you can read here.

    Python Code:

    sample_list = ["my", "programming", "tutorial"]
    capitalize_list = [word.title() for word in sample_list]
    print("Capitalize words List",capitalize_list)

    Output:-

    Capitalize words List ['My', 'Programming', 'Tutorial']

    How to capitalize each word in file

    To manually capitalize every word in any given file is not convenient. It is very easy by using python. We can do this by each reading file line by line and using the string title() method on each line.

    Python Code:

    file = file = open(any_file.txt', 'r')
    for line in file:
    	print(line.title())

    Output:-

    Welcome To My Programming Tutorial.!

    Conclusion

    Hence we have discuss python capitalize first letter in string. We can do this by using python methods like the title(), string.capwords(), capitalize(). We can use regex, list comprehension, and string slicing to capitalize each word in string in python.

    I am Passionate Computer Engineer. Writing articles about programming problems and concepts allows me to follow my passion for programming and helping others.

    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 capitalizes string method is used to converts the first character of a string (first letter of the first word in the sentence) to the capital (uppercase) letter. The string will same if the string has the first character capital.

    Python capitalize String method First, all or every Letter example

    Syntax

    The capitalize() method returns a string where the first letter is upper case. And this method does not take any parameter.

    string.capitalize()
    

    Python capitalize the first letter of a sentence

    This is a simple example of how to use the capitalize() method in python. The output should be uppercase of the first letter.

    txt_str = "hello, and welcome to my world."
    x = txt_str.capitalize()
    
    print(x)
    
    

    Output: Hello, and welcome to my world.

    Interview Questions & Answer

    Q: How to Python capitalize all letters?

    Answer: To change a string into uppercase in use upper() method in python.

    txt_str = "hello, and welcome to my world."
    
    x = txt_str.upper()
    
    print(x)
    

    Q: How to Python capitalize the first letter of every word in a string?

    Answer: To capitalize the first letter of each word in a string use title() method in python.

    txt_str = "hello, and welcome to my world."
    
    x = txt_str.title()
    
    print(x)
    
    

    Q: What happens if the first character is a number?

    Answer: If in a sentence first, character (letter) is is number then nothing will change in a sentence. Try out yourself with Non-alphabetic First Character and do comment.

    txt_str = "7 hello, and welcome to my world."
    
    x = txt_str.capitalize()
    
    print(x)
     

    Output: 7 hello, and welcome to my world.

    Related article: Python uppercase function upper() | convert string to Uppercase

    Do comment if you have any doubts and suggestions on the tutorial.

    Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
    JRE: 1.8.0
    JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
    macOS 10.13.6
    Python 3.7
    All Examples of Python capitalize are in Python 3, so it may change its different from python 2 or upgraded versions.

    Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.

    Like this post? Please share to your friends:
  • Python capitalize each word in string
  • Python make excel file
  • Python load from excel
  • Python api for excel
  • Python and word documents