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, 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 booleanOR
. 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
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.
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 –
- 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. - For each word, capitalize the first letter using the string
upper()
function. - 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 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
Strings are one of the most used python data structures. While programming in python, some strings are used in uppercase while some are in lowercase and some in combination. Hence, it is chaotic to pay attention to every string you create and use while programming, and also quite difficult to correct it manually.
As it is important and default format to capitalize the first letter of every word for readers convenience, we have presented a detailed article representing 8 different methods to capitalize the first letter in python and the examples. But, before learning those methods, let us have a brief introduction to strings in python.
What are Strings in Python?
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The computer does not understand the characters; internally, it stores manipulated characters as the combination of the 0’s and 1’s. This means that strings can be parsed into individual characters and that individual characters can be manipulated in various ways.
This is what makes Python so versatile: you can do almost anything with it, and some things even work the way they do in another language. To learn more about strings in python, refer to our article «4 Ways to Convert List to String in Python».
For Example
Output
How to Capitalize the First Letter in Python?
Below are the eight methods to capitalize the first letter of strings in python:
1) Using str.capitalize() to capitalize first letter
The string.capitalize () function takes the string argument and returns the first letter of the capitalized word. This can be useful if you have a lot of text that you want to format as uppercase automatically or if you want to change the file’s name or folder. The function works on any string containing English letters, numbers, and punctuation marks.
For Example
s = "python" print("Original string:") print(s) print("After capitalizing first letter:") print(s.capitalize())
Output
Original string: python After capitalizing first letter: Python
2) Using string slicing() and upper() method
We used the slicing technique to extract the string’s first letter in this method. We then used the upper() method of string manipulation to convert it into uppercase. This allows you to access the first letter of every word in the string, including the spaces between words. The below example shows the working of this method in detail.
For Example
s = "python" print("Original string:") print(s) result = s[0].upper() + s[1:] print("After capitalizing first letter:") print(result)
Output
Original string: python After capitalizing first letter: Python
3) Using str.title() method
string.title() method is a very simple and straightforward method of generating titles for strings. As the titles for string have a default structure where the first letter is always in upper case, this method helps us capitalize the first letter of every word and change the others to lowercase, thus giving the desired output. This method is also useful for formatting strings in HTML and formatting strings in JavaScript and other programming languages.
For Example
s = "python" print("Original string:") print(s) print("After capitalizing first letter:") print(str.title(s))
Output
Original string: python After capitalizing first letter: Python
When we use the entire sentence as the input string, it will capitalize the first letter of every word in the string, as shown below.
For Example
s = "it's DIFFICULT to identify 10a " # Capitalize the first letter of each word result = s.title() print(result)
Output
It isn't easy To Identify 10A
The behaviors drawn from the above example are:
- “DIFFICULT” is converted into “Difficult” because the title function only capitalizes the first letter of every word and keeps the remaining characters of the word as lower case.
- “it’s” is converted to «It’S” because the function considers “it’s” as two separate words by considering apostrophes.
- “10a” is converted to “10A” because the title function considers “as the first character for the word “a.»
4) Using capitalize() function to capitalize the first letter of each word in a string
Here, we make use of the split() method to split the given string into words. The generator expression iterates through the words, using the capitalize() method to convert the first letter of each word into uppercase. The capitalize() method converts each word’s first letter to uppercase, giving the desired output. The below example shows the working of the capitalize function in detail.
Example
s = "python" print("Original string:") print(s) print("After capitalizing first letter:") result = ' '.join(elem.capitalize() for elem in s.split()) print(result)
Output
Original string: python After capitalizing first letter: Python
5) Using string.capwords()
capwords() is a python function that converts the first letter of every word into uppercase and every other letter into lowercase. The function takes the string as the parameter value and then returns the string with the first letter capital as the desired output. Check out the below example to understand the working of the capwords() function.
For Example
import string s = "python" print("Original string:") print(s) print("After capitalizing first letter:") result = string.capwords(s) print(result)
Output
Original string: python After capitalizing first letter: Python
6) Using regex to capitalize the first letter in python
Regex is generally known as a regular expression in python, is a special sequence of characters that helps match or find the other strings. Using regex, you can search the starting character of each word and capitalize it. For using this method, you have to import the regex library using the “import” keyword before defining the main function, as shown in the below example. Also, remember that this method only capitalizes the first character of each word in python and does not modify the whitespaces between the words.
For Example
import re def convert_into_uppercase(a): return a.group(1) + a.group(2).upper() s = "python is best programming language" result = re.sub("(^|s)(S)", convert_into_uppercase, s) print(result)
Output
Python Is Best Programming Language
7) Capitalize the first letter of every word in the list
You must wonder how difficult it would be if we had an entire list of words as a string instead of a single string to capitalize the first letter in python. Well, it is quite simple. When you have an entire list of words and wish to capitalize the first letter of every word, you can iterate through the words in the list using for loop and then use the title() method in python. This process will help you to convert the first letter of each word in the list to uppercase.
For Example
fruits=['apple','grapes','orange'] print('Original List:') print(fruits) fruits = [i.title() for i in fruits] print('List after capitalizing each word:') print(fruits)
Output
Original List: ['apple', 'grapes', 'orange'] List after capitalizing each word: ['Apple', 'Grapes', 'Orange']
Capitalize the first letter of each word in the file
Capitalizing the first letter of any given the word manually is quite feasible, but what if you have to capitalize the first letter of every word in any given file? Well, it is quite easy too. For this situation, you have to use the open() method to open the file in the reading mode and then iterate through every word using for loop. Later, you can capitalize the first letter of every word using the title() function, just like shown in the below example.
For Example
file = open('readme.txt', 'r') for line in file: output = line.title() print(output)
Output
Hello! Welcome To Favtutor
Conclusion
As strings are frequently used data structure while programming in python, it is not feasible to capitalize the first letter of each string word manually. Hence, we have presented various ways to convert the first letter in the string as uppercase. All these functions draw the same output, and hence you can choose the one according to your need. However, if you face any difficulty, get in touch with our python tutors to solve your doubts.