How do you capitalize the first letter in python without changing the rest?

I'm wanting to capitalize the fist letter of a string but leave the rest

What I have: racEcar

What I want: RacEcar

asked Aug 2, 2015 at 0:49

How do you capitalize the first letter in python without changing the rest?

0

Then just capitalize the first letter with str.upper() and concatenate the rest unchanged

string[0].upper() + string[1:]

Demo:

>>> string = 'racEcar'
>>> string[0].upper() + string[1:]
'RacEcar'

answered Aug 2, 2015 at 0:52

Martijn PietersMartijn Pieters

986k274 gold badges3877 silver badges3236 bronze badges

0

You should do like Martijn suggests, but to make your function more robust, slice up to the first letter, so that you don't error on an empty string:

>>> rc = 'racEcar'
>>> newrc = rc[:1].upper() + rc[1:]
>>> newrc
'RacEcar'

so define a function that does this:

def capfirst(s):
    return s[:1].upper() + s[1:]

and then:

>>> capfirst(rc)
'RacEcar'
>>> capfirst('')
''

answered Aug 2, 2015 at 0:58

How do you capitalize the first letter in python without changing the rest?

2

This has already been stated but I decided to show it.

Using capitalize() does what you want without extra work. For example,

def Cap1(string):
    # will not error if empty, and only does the first letter of the first word.
    return string.capitalize()

Using title() may require extra work if you have multiple words. For example,

let's assume your string is: "i want pizza"

def cap2(string):
    return string.title()

The output would be: "I Want Pizza"

Another way you can use upper() is:

def cap3(string):
    if not len(string) == 0: 
        return string[0].upper()

answered Aug 2, 2015 at 2:13

1

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:

  1. “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.
  2. “it's” is converted to "It'S” because the function considers “it's” as two separate words by considering apostrophes.
  3. “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']

8) 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.

How do you change only first letter in capitalize in Python?

string capitalize() in Python 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.

How do you capitalize the first letter of a variable in Python?

Use title() to capitalize the first letter of each word in a string in python. 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.

How do you capitalize the first letter and lowercase rest in Python?

Python has a built-in method named capitalize() to convert the first character of a string into uppercase and change the rest of the characters into lowercase. This method can be used on string data in various ways without just capitalizing on the first characters.

How do you capitalize text in Python?

Python String capitalize() The capitalize() method converts the first character of a string to an uppercase letter and all other alphabets to lowercase.