Home » Python

Python | string.upper(), string.lower() and string.title() Methods with Examples

In this article, we are going to learn about the Python's inbuilt methods string.upper(), string.lower() and string.title() with Examples.
Submitted by IncludeHelp, on August 29, 2018

string.upper(), string.lower() and string.title() Methods are inbuilt methods in Python, these are used to format string in a particular format like uppercases, lowercase or little case format.

1) string.upper()

Method returns uppercase string (where all characters of the string are in uppercase).

Example: "HELLO WORLD"

2) string.lower()

Method returns lowercase string (where all characters of the string are in lowercase).

Example: "hello world"

3) string.upper()

Method returns title case string (where first character of the each words are in uppercase, rest of all characters are in lowercase).

Example: "Hello World"

Syntaxes:

    string.upper()
    string.lower()
    string.title()

Example 1:

# declare a string 
str = "HELLO World How are you?"

# uppercase string 
print "Uppercase string: ",str.upper()

# lowercase string
print "Lowercase string: ",str.lower()

# title case string
print "Title case string: ",str.title()

Output

    Uppercase string:  HELLO WORLD HOW ARE YOU?
    Lowercase string:  hello world how are you?
    Title case string:  Hello World How Are You?

Example 2: Change string case – if string is in uppercase, convert it to lowercase and if it is in lowercase convert it to uppercase.

There is a string, we have to change its case, if string is in uppercase convert it to lowercase. If string is in lowercase convert it to uppercase, otherwise convert string into title case.

# function to check and change case 
def changeCase(str) :
	
	if(str.isupper()):
		str = str.lower()
	elif(str.islower()):
		str = str.upper()
	else: 
		str = str.title()
	
	return str;

	
# Main code 
str = "HELLO WORLD"
print changeCase(str)

str = "hello world"
print changeCase(str)

str = "HELLO world"
print changeCase(str)

Output

    hello world
    HELLO WORLD
    Hello World


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.