Python 3 – String istitle() Method
In Python, strings are used to store and manipulate textual data. The istitle()
method is a built-in method of the string data type in Python that checks if each word in a string begins with an uppercase letter and the remaining letters are in lowercase. The method returns a boolean value of True
if the string satisfies this condition, and False
otherwise.
Syntax
string.istitle()
Parameters
The istitle()
method does not take any parameters.
Return Value
The istitle()
method returns a boolean value of True
if the string satisfies the condition, and False
otherwise.
Example
Let’s look at an example to understand the istitle()
method.
string1 = "Hello World"
string2 = "this Is a Sentence"
string3 = "this is not a title"
print(string1.istitle()) # True
print(string2.istitle()) # True
print(string3.istitle()) # False
In the above code, we have defined three string variables, string1
, string2
, and string3
. We then call the istitle()
method on each of these strings and print the resulting boolean value. The output shows that string1
and string2
satisfy the condition and return True
, while string3
does not satisfy the condition and returns False
.
Usage
The istitle()
method is commonly used in text processing applications where we need to check if a given string is a title. A title is a string where the first letter of each word is capitalized and the remaining letters are in lowercase.
Example
Suppose we want to validate user input for a name field in our application. We want the user to enter their full name in the format “First Name Last Name”. We can use the istitle()
method to check if the input string conforms to this format.
while True:
name = input("Enter your name in the format 'First Name Last Name': ")
if name.istitle():
print("Name is valid")
break
else:
print("Name is not valid")
In the above code, we use a while loop to repeatedly ask the user for their name until they enter a valid name in the format “First Name Last Name”. We call the istitle()
method on the input string and check if it returns True
. If it does, we print a message indicating that the name is valid, and exit the loop. Otherwise, we print a message indicating that the name is not valid, and ask the user to enter their name again.
Conclusion
In this article, we discussed the istitle()
method of the string data type in Python. We saw how the method checks if a string is a title (i.e., if each word begins with an uppercase letter and the remaining letters are in lowercase). We also saw how the method can be used in text processing applications to validate user input for a name field or check if a given string is a title.