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!
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.
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
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
Hello coders!! In this article, we will be learning how one can capitalize the first letter in the string in Python. There are different ways to do this, and we will be discussing them in detail. Let us begin!
- Syntax: string.capitalize()
- Parameters: no parameters
- Return Value: string with the first capital first letter
string = "python pool" print("Original string:") print(string) print("After capitalizing first letter:") print(string.capitalize())
Output & Explanation:
When we use the capitalize() function, we convert the first letter of the string to uppercase. In this example, the string we took was “python pool.” The function capitalizes the first letter, giving the above result.
Method 2: string slicing + upper():
- Synatx: string.upper()
- Parameters: No parameters
- Return Value: string where all characters are in upper case
string = "python pool" print("Original string:") print(string) result = string[0].upper() + string[1:] print("After capitalizing first letter:") print(result)
Output & Explanation:
We used the slicing technique to extract the string’s first letter in this example. We then used the upper() method to convert it into uppercase.
Method 3: str.title():
- Syntax: str.title()
- Parameters: a string that needs to be converted
- Return Value: String with every first letter of every word in capital
string = "python pool" print("Original string:") print(string) print("After capitalizing first letter:") print(str.title(string))
Output & Explanation:
str.title() method capitalizes the first letter of every word and changes the others to lowercase, thus giving the desired output.
Method 4: capitalize() Function to Capitalize the first letter of each word in a string in Python
string = "python pool" print("Original string:") print(string) print("After capitalizing first letter:") result = ' '.join(elem.capitalize() for elem in string.split()) print(result)
Output & Explanation:
In this example, we used the split() method to split the string into words. We then iterated through it with the help of a generator expression. While iterating, we used the capitalize() method to convert each word’s first letter into uppercase, giving the desired output.
Method 5: string.capwords() to Capitalize first letter of every word in Python:
- Syntax: string.capwords(string)
- Parameters: a string that needs formatting
- Return Value: String with every first letter of each word in capital
import string txt = "python pool" print("Original string:") print(txt) print("After capitalizing first letter:") result = string.capwords(txt) print(result)
Output & Explanation:
capwords() function not just convert the first letter of every word into uppercase. It also converts every other letter to lowercase.
Method 6: Capitalize the first letter of every word in the list in Python:
colors=['red','blue','yellow','pink'] print('Original List:') print(colors) colors = [i.title() for i in colors] print('List after capitalizing each word:') print(colors)
Output & Explanation:
Iterate through the list and use the title() method to convert the first letter of each word in the list to uppercase.
Method 7:Capitalize first letter of every word in a file in Python
file = open('sample1.txt', 'r') for line in file: output = line.title() print(output)
Output & Explanation:
Python Pool Is Your Ultimate Destination For Your Python Knowledge
We use the open() method to open the file in read mode. Then we iterate through the file using a loop. After that, we capitalize on every word’s first letter using the title() method.
You might be interested in reading:
- How to Convert String to Lowercase in Python
- How to use Python find() | Python find() String Method
- Python Pass Statement| What Does Pass Do In Python
- How to Count Words in a String in Python
Conclusion:
The various ways to convert the first letter in the string to uppercase are discussed above. All functions have their own application, and the programmer must choose the one which is apt for his/her requirement.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
Happy Pythoning!
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
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.
Improve Article
Save Article
Like Article
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
In JavaScript, there is a lot of different ways to capitalize the first letter of a string.
You can capitalize the first letter with a combination of built-in javascript functions, with regex expressions and, even with CSS.
Read this article to find out your favorite new way. 😎
Page content
- How to capitalize the first letter in JavaScript?
- How to capitalize the first letter of each word?
- How to capitalize all the letters in a word?
- Final Thoughts
How to capitalize the first letter in JavaScript?
1. Using the charAt() with the slice() function
To capitalize the first letter of a string you need to follow these steps:
- Get the first character with the charAt() function
- Uppercase it with the toUpperCase() function.
- Concatenate the rest of the string to the uppercased character.
javascriptconst str = "this is a very long string!";
// This will return: "This is a very long string!"
console.log(str.charAt(0).toUpperCase() + str.slice(1));
Read more: The slice function
2. Using the replace() function
You can also capitalize the first letter of a string by using the replace() function and a regex.
- You create a regex that will only match the first character (this is the regex: /./).
- With the replace() function, you uppercase the first character by matching the regex.
typescriptconst str = "this is a very long string!";
// This will return: "This is a very long string!"
console.log(str.replace(/./, c => c.toUpperCase()));
3. Using CSS
You can also capitalize the first letter using the CSS text-transform property and the ::first-letter selector.
xml<div id="my_title">this is a very long string!</div>
<style>
#my_title::first-letter {
text-transform: capitalize;
}
</style>
4. Using Lodash
Alternatively, you can use lodash to do this for you.
Lodash has a special capitalize() function.
javascriptconst str = "this is a very long string!";
_.capitalize(str);
How to capitalize the first letter of each word?
1. Using a regex
To capitalize the first letter of each word you can use the replace() function with a regex.
typescriptconst str = 'this is a very long string!';
// This will return: "This Is A Very Long String!"
console.log(str.replace(/(^w|sw)/g, m => m.toUpperCase()));
Here is a table explaining this regex:
Characters | Meaning |
---|---|
^ | Matches the beginning of an input. |
w | Matches any alphanumeric character. |
s | Matches a single whitespace character. |
The g modifier means global. It means that the regex will find all matches.
2. Using the map() function
Also, you can capitalize the first letter of each word by following these steps:
- Make all the text lowercase.
- Split all the words inside an array.
- Iterate through each word inside the array using the map() function and uppercase the first letter.
- Transform the array into a string using the join() function.
typescriptlet str = 'this is a very long string!';
str = str.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
// This will return: "This Is A Very Long String!"
console.log(str);
3. Using a for loop
You can also capitalize the first letter of each word by looping through each word with a for loop using the length property.
javascriptconst words = 'this is a very long string!'.split(" ");
for (let i = 0; i < words.length; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
const str = words.join(' ');
// This will return: "This Is A Very Long String!"
console.log(str);
4. Using CSS
If you don’t want to use JavaScript, we have good news for you!
You can use the CSS text-transform property to archive the same result.
xml<div id="my_title">this is a very long string!</div>
<style>
#my_title {
text-transform: capitalize;
}
</style>
How to capitalize all the letters in a word?
To capitalize all the letters of a string you need to use the toUpperCase() built-in function. You learn more by reading the article that I have written about the toUpperCase function.
Final Thoughts
As you can see, there is a lot of different ways to choose from when you want to capitalize the first letter of a string.
In my case, when I develop a new application, I create a helper function called capitalize(str: string) in my utils file and import it whenever I need to use it.
I hope you liked this article, please share it!
written by:
Hello! I am Tim Mouskhelichvili, a Freelance Developer & Consultant from Montreal, Canada.
I specialize in React, Node.js & TypeScript application development.
If you need help on a project, please reach out, and let’s work together.