Word capitalize first letter of each word

You can change the capitalization, or case, of selected text in a document by clicking a single button on the Home tab called Change Case.

Change case

To change the case of selected text in a document, do the following:

  1. Select the text for which you want to change the case.

  2. Go to Home > Change case  .

  3. Do one of the following:

    • To capitalize the first letter of a sentence and leave all other letters as lowercase, click Sentence case.

    • To exclude capital letters from your text, click lowercase.

    • To capitalize all of the letters, click UPPERCASE.

    • To capitalize the first letter of each word and leave the other letters lowercase, click Capitalize Each Word.

    • To shift between two case views (for example, to shift between Capitalize Each Word and the opposite, cAPITALIZE eACH wORD), click tOGGLE cASE.

    Tips: 

    • To apply small capital (Small Caps) to your text, select the text, and then on the Home tab, in the Font group, click the arrow in the lower-right corner. In the Font dialog box, under Effects, select the Small Caps check box.

    • To undo the case change, press CTRL+ Z.

    • To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and press SHIFT + F3 until the case you want is applied.

See also

Insert a drop cap

Choose AutoCorrect options for capitalization

Change case

To change the case of selected text in a document, do the following:

  1. Select the text for which you want to change the case.

  2. Go to Home > Change case  .

  3. Do one of the following:

    • To capitalize the first letter of a sentence and leave all other letters as lowercase, click Sentence case.

    • To exclude capital letters from your text, click lowercase.

    • To capitalize all of the letters, click UPPERCASE.

    • To capitalize the first letter of each word and leave the other letters lowercase, click Capitalize Each Word.

    • To shift between two case views (for example, to shift between Capitalize Each Word and the opposite, cAPITALIZE eACH wORD), click tOGGLE cASE.

    Tips: 

    • To apply small capital (Small Caps) to your text, select the text, and then on the Format menu, select Font, and in the Font dialog box, under Effects, select the Small Caps box.

      Small Caps shortcut key: ⌘ + SHIFT + K

    • To undo the case change, press ⌘ + Z .

    • To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and then press fn+ SHIFT + F3 until the style you want is applied.

See also

Insert a drop cap

Choose AutoCorrect options for capitalization

PowerPoint for the web supports changing case. See the procedure below.

Word for the web doesn’t support changing case. Use the desktop application to open the document and change text case there, or else you can manually change the casing of text in Word for the web.

  1. Select the text you want to change.

  2. Go to Home > More Font Options > Change case.

    Select the "More Font Options" ellipsis button, select Change Case, and then select the option you want.

  3. Choose the case you want to use.

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!

In this article we will discuss 5 different ways to convert first letter of each word in a string to uppercase. We will also discuss what are the limitations of each approach and which one is best for us.

Python Str class provides a member function title() which makes each word title cased in string. It means, it converts the first character of each word to upper case and all remaining characters of word to lower case.

Let’s use this to capitalize the first letter of each word in a string,

sample_text = "this is a sample string"

# Capitalize the first letter of each word i.e.
# Convert the first letter of each word to Upper case and all other to lower case
result = sample_text.title()

print(result)

Output:

Advertisements

This Is A Sample String

It worked fine with this solution, but there is a caveat. The title() function not only capitalize the first letter of each word in a string but also makes all remaining characters of each word to upper case. For example,

sample_text = "33a. it's GONE too far"

# Capitalize the first letter of each word
result = sample_text.title()

print(result)

Output:

33A. It'S Gone Too Far

There are 3 unexpected behaviors in above example,

  • In this example it converted “GONE” to “Gone”, because for each word in string it makes only first character as upper case and all remaining characters as lower case.
  • It converted “it’s” to “It’S” , because it considered “it’s” as two separate words.
  • It converted “33a” to “33A” , because it considered “a” as the first letter of word ’33a’.

So, title() function is not the best solution for capitalizing the first letter of each word in a string. Let’s discuss an another solution,

Use capitalize() to capitalize the first letter of each word in a string

Python’s Str class provides a function capitalize(), it converts the first character of string to upper case. Where as it is already in upper case then it does nothing.

We can use this capitalize() to capitalize the first letter of each word in a string. For that, we need to split our string to a list of words and then on each word in the list we need to call the capitalize() function. Then we need to join all the capitalized words to form a big string.

Let’s understand this with an example,

def capitalize_each_word(original_str):
    result = ""
    # Split the string and get all words in a list
    list_of_words = original_str.split()
    # Iterate over all elements in list
    for elem in list_of_words:
        # capitalize first letter of each word and add to a string
        if len(result) > 0:
            result = result + " " + elem.strip().capitalize()
        else:
            result = elem.capitalize()
    # If result is still empty then return original string else returned capitalized.
    if not result:
        return original_str
    else:
        return result

sample_text = "33a. it's GONE too far"

result = capitalize_each_word(sample_text)

print(result)

Output:

33a. It's Gone Too Far

It converted the first letter of each word in string to upper case.

Instead of writing the big function, we can achieve same using generator expressions i.e.

sample_text = "33a. it's GONE too far"

result = ' '.join(elem.capitalize() for elem in sample_text.split())

print(result)

Output:

33a. It's Gone Too Far

Here we split the string to words and iterated our each word in string using generator expression. While iterating, we called the capitalized() function on each word, to convert the first letter to uppercase and the joined that word to a string using ‘ ‘ as delimiter.

It served the purpose, but there can be one issue in this approach i.e. if words in original string are separated by more than one white spaces or tabs etc. Then this approach can cause error, because we are joining all capitalized words using same delimiter i.e. a single white space. Checkout this example,

sample_text = "this     is       a      sample   string"

result = ' '.join(elem.capitalize() for elem in sample_text.split())

print(result)

Output:

This Is A Sample String

Here original string had multiple spaces between words, but in our final string all capitalized words are separated by a single white space. For some this might not be the correct behavior. So, to rectify this problem checkout our next approach.

Using string.capwords() to capitalize the first letter of each word in a string

Python’s string module provides a function capwords() to convert the first letter to uppercase and all other remaining letters to lower case.
It basically splits the string to words and after capitalizing each word, joins them back using a given seperator. Checkout this example,

import string

sample_text = "it's gone tOO far"

result = string.capwords(sample_text)

print(result)

Output:

It's Gone Too Far

Problem with is solution is that it not only converts the first letter of word to uppercase but also makes the remaining letters of word to lower case. For some, this might not be the correct solution.

So, let’s discuss our final and best solution that does what’s only expected from it.

Using Regex to capitalize the first letter of each word in a string

Using regex, we will look for the starting character of each word and the convert to uppercase. For example,

import re

def convert_to_uupercase(m):
    """Convert the second group to uppercase and join both group 1 & group 2"""
    return m.group(1) + m.group(2).upper()

sample_text = "it's gone   tOO far"

result = re.sub("(^|s)(S)", convert_to_uupercase, sample_text)

print(result)

Output:

It's Gone   TOO Far

It capitalized only first character of each word in string and do not modifies the whitespaces between words.

How did it worked ?

We created use a pattern “(^|s)(S)”. It looks for string patterns that starts with zero or more whitespaces and then has a non whitespace character after that. Then for each matching instance, it grouped both initial whitespaces and the first character as separate groups. Using regex.sub() function, we passed each matching instance of the pattern to a function convert_to_uppercase(), which converts the second group i.e. first letter of word to upper case and then joins it with the first group(zero or more white spaces).

For string,

sample_text = "it's gone tOO far"

The function convert_to_uupercase() was called 4 times by regex.sub() and in each call group 1 & 2 of match object were,

'' and 'i'
' ' and 'g'
' ' and 't'
' ' and 'f'

Inside convert_to_uupercase(), it converted the second group i.e. first character of each word to uppercase.

So, this is how we can capitalize the first letter of each word in a string using regex and without affecting any other character of the string.

The complete example is as follows,

import string
import re


def capitalize_each_word(original_str):
    result = ""
    # Split the string and get all words in a list
    list_of_words = original_str.split()
    # Iterate over all elements in list
    for elem in list_of_words:
        # capitalize first letter of each word and add to a string
        if len(result) > 0:
            result = result + " " + elem.strip().capitalize()
        else:
            result = elem.capitalize()
    # If result is still empty then return original string else returned capitalized.
    if not result:
        return original_str
    else:
        return result


def main():

    print('*** capitalize the first letter of each word in a string ***')

    print('*** Use title() to capitalize the first letter of each word in a string ***')

    print('Example 1:')
    sample_text = "this is a sample string"
    # Capitalize the first letter of each word i.e.
    # Convert the first letter of each word to Upper case and all other to lower case
    result = sample_text.title()

    print(result)

    print('Example 2:')

    sample_text = "33a. it's GONE too far"

    # Capitalize the first letter of each word
    result = sample_text.title()

    print(result)

    print('*** Use capitalize() to capitalize the first letter of each word in a string ***')

    sample_text = "33a. it's GONE too far"

    result = capitalize_each_word(sample_text)

    print(result)

    print('Using capitalize() and generator expression')

    result = ' '.join(elem.capitalize() for elem in sample_text.split())

    print(result)

    print('Example 2:')

    sample_text = "this     is       a      sample   string"

    result = ' '.join(elem.capitalize() for elem in sample_text.split())

    print(result)

    print('*** Using string.capwords() to capitalize the first letter of each word in a string ***')

    sample_text = "it's gone tOO far"

    result = string.capwords(sample_text)

    print(result)

    print('*** Using Regex to capitalize the first letter of each word in a string ***')

    sample_text = "it's gone   tOO far"

    result = re.sub("(^|s)(S)", convert_to_uupercase, sample_text)

    print(result)

def convert_to_uupercase(m):
    """Convert the second group to uppercase and join both group 1 & group 2"""
    return m.group(1) + m.group(2).upper()

if __name__ == '__main__':
    main()

Output:

*** capitalize the first letter of each word in a string ***
*** Use title() to capitalize the first letter of each word in a string ***
Example 1:
This Is A Sample String
Example 2:
33A. It'S Gone Too Far
*** Use capitalize() to capitalize the first letter of each word in a string ***
33a. It's Gone Too Far
Using capitalize() and generator expression
33a. It's Gone Too Far
Example 2:
This Is A Sample String
*** Using string.capwords() to capitalize the first letter of each word in a string ***
It's Gone Too Far
*** Using Regex to capitalize the first letter of each word in a string ***
It's Gone   TOO Far

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

How to Capitalize the First Letter of Each Word in JavaScript – a JS Uppercase Tutorial

In this article, you are going to learn how to capitalize the first letter of any word in JavaScript. After that, you are going to capitalize the first letter of all words from a sentence.

The beautiful thing about programming is that there is no one universal solution to solve a problem. Therefore, in this article you are going to see multiple ways of solving the same problem.

First of all, let’s start with capitalizing the first letter of a single word. After you learn how to do this, we’ll proceed to the next level – doing it on every word from a sentence. Here is an example:

const publication = "freeCodeCamp";

In JavaScript, we start counting from 0. For instance, if we have an array, the first position is 0, not 1.

Also, we can access each letter from a String in the same way that we access an element from an array. For instance, the first letter from the word «freeCodeCamp» is at position 0.

This means that we can get the letter f from freeCodeCamp by doing publication[0].

In the same way, you can access other letters from the word. You can replace «0» with any number, as long as you do not exceed the word length. By exceeding the word length, I mean trying to do something like publication[25, which throws an error because there are only twelve letters in the word «freeCodeCamp».

How to capitalize the first letter

Now that we know how to access a letter from a word, let’s capitalize it.

In JavaScript, we have a method called toUpperCase(), which we can call on strings, or words. As we can imply from the name, you call it on a string/word, and it is going to return the same thing but as an uppercase.

For instance:

const publication = "freeCodeCamp";
publication[0].toUpperCase();

Running the above code, you are going to get a capital F instead of f. To get the whole word back, we can do this:

const publication = "freeCodeCamp";
publication[0].toUpperCase() + publication.substring(1);

Now it concatenates «F» with «reeCodeCamp», which means we get back the word «FreeCodeCamp». That is all!

Let’s recap

To be sure things are clear, let’s recap what we’ve learnt so far:

  • In JavaScript, counting starts from 0.
  • We can access a letter from a string in the same way we access an element from an array — e.g. string[index].
  • Do not use an index that exceeds the string length (use the length method — string.length — to find the range you can use).
  • Use the built-in method toUpperCase() on the letter you want to transform to uppercase.

Capitalize the first letter of each word from a string

The next step is to take a sentence and capitalize every word from that sentence. Let’s take the following sentence:

const mySentence = "freeCodeCamp is an awesome resource";

Split it into words

We have to capitalize the first letter from each word from the sentence freeCodeCamp is an awesome resource.

The first step we take is to split the sentence into an array of words. Why? So we can manipulate each word individually. We can do that as follows:

const mySentence = "freeCodeCamp is an awesome resource";
const words = mySentence.split(" ");

Iterate over each word

After we run the above code, the variable words is assigned an array with each word from the sentence. The array is as follows ["freeCodeCamp", "is", "an", "awesome", "resource"].

const mySentence = "freeCodeCamp is an awesome resource";
const words = mySentence.split(" ");

for (let i = 0; i < words.length; i++) {
    words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}

Now the next step is to loop over the array of words and capitalize the first letter of each word.

In the above code, every word is taken separately. Then it capitalizes the first letter, and in the end, it concatenates the capitalized first letter with the rest of the string.

Join the words

What is the above code doing? It iterates over each word, and it replaces it with the uppercase of the first letter + the rest of the string.

If we take «freeCodeCamp» as an example, it looks like this freeCodeCamp = F + reeCodeCamp.

After it iterates over all the words, the words array is ["FreeCodeCamp", "Is", "An", "Awesome", "Resource"]. However, we have an array, not a string, which is not what we want.

The last step is to join all the words to form a sentence. So, how do we do that?

In JavaScript, we have a method called join, which we can use to return an array as a string. The method takes a separator as an argument. That is, we specify what to add between words, for example a space.

const mySentence = "freeCodeCamp is an awesome resource";
const words = mySentence.split(" ");

for (let i = 0; i < words.length; i++) {
    words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}

words.join(" ");

In the above code snippet, we can see the join method in action. We call it on the words array, and we specify the separator, which in our case is a space.

Therefore, ["FreeCodeCamp", "Is", "An", "Awesome", "Resource"] becomes FreeCodeCamp Is An Awesome Resource.

Other methods

In programming, usually, there are multiple ways of solving the same problem. So let’s see another approach.

const mySentence = "freeCodeCamp is an awesome resource";
const words = mySentence.split(" ");

words.map((word) => { 
    return word[0].toUpperCase() + word.substring(1); 
}).join(" ");

What is the difference between the above solution and the initial solution? The two solutions are very similar, the difference being that in the second solution we are using the map function, whereas in the first solution we used a for loop.

Let’s go even further, and try to do a one-liner. Be aware! One line solutions might look cool, but in the real world they are rarely used because it is challenging to understand them. Code readability always comes first.

const mySentence = "freeCodeCamp is an awesome resource";

const finalSentence = mySentence.replace(/(^w{1})|(s+w{1})/g, letter => letter.toUpperCase());

The above code uses RegEx to transform the letters. The RegEx might look confusing, so let me explain what happens:

  • ^ matches the beginning of the string.
  • w matches any word character.
  • {1} takes only the first character.
  • Thus, ^w{1} matches the first letter of the word.
  • | works like the boolean OR. It matches the expression after and before the |.
  • s+ matches any amount of whitespace between the words (for example spaces, tabs, or line breaks).

Thus, with one line, we accomplished the same thing we accomplished in the above solutions. If you want to play around with the RegEx and to learn more, you can use this website.

Conclusion

Congratulations, you learnt a new thing today! To recap, in this article, you learnt how to:

  • access the characters from a string
  • capitalize the first letter of a word
  • split a string in an array of words
  • join back the words from an array to form a string
  • use RegEx to accomplish the same task

Thanks for reading! If you want to keep in touch, let’s connect on Twitter @catalinmpit. I also publish articles regularly on my blog catalins.tech if you want to read more content from me.



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
  • Word cannot save document
  • Word cannot open this
  • Word cannot open document access privileges
  • Word cannot be touched
  • Word cannot be rhymed