Online Tutorials & Training Materials |
Register Login

How to Capitalize a String in Python?

|| 0

How to Capitalize a String in Python?

In python when we need first character of any given string in uppercase or capital letter and rest of the character present in the original string in lowercase or small letter, then we use python capitalize() function.



Parameters: It doesn't take any parameters.


1.If the first character of original string is already uppercase then it will return the original string.

2.If the first character is non character, It will leave the first character as it is and lowercase all the other characters in present in original string.

3.This function will not change the value of original variable.


# Python code to explain capitalize() function 
# Initialize a string with all lowercase characters
str1 = 'smart techies'

# Initialize a string with first uppercase character
str2 = 'Smart techies'

# Initialize a string with all uppercase character

# Initialize a string with first numeric character
str4 = '1SMART Techies'

# Pass strings with capitalize() function
capstr1 = str1.capitalize()
capstr2 = str2.capitalize()
capstr3 = str3.capitalize()
capstr4 = str4.capitalize()

# Print output
print('String 1: ', str1, ' New 1: ',capstr1)
print('String 2: ', str2, ' New 2: ',capstr2)
print('String 3: ', str3, ' New 3: ',capstr3)
print('String 4: ', str4, ' New 4: ',capstr4)


String 1:  smart techies  New 1:  Smart techies
String 2:  Smart techies  New 2:  Smart techies
String 3:  SMART TECHIES  New 3:  Smart techies
String 4:  1SMART Techies  New 4:  1smart techies