Close
Close

Python Strings


You have already been introduced with strings. Like a list, a string is also a sequence. It is a sequence of characters.

Creating a String in Python


A string is created by enclosing the sequence of characters within single quotes ' ' or double quotes " ". Therefore, 'Hello World' and "Hello World" both are strings.

mystring = 'Hello World'
print(mystring)
print(type(mystring))
Output
Hello World <class 'str'>
mystring = "Hello World"
print(mystring)
print(type(mystring))
Output
Hello World <class 'str'>

As we mentioned that a string is a sequence of characters, the string “Hello World” is a sequence of 11 characters - ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’. Yes, space is also a character. In fact, all the alphabets, digits, punctuation marks, space, or any other special character enclosed within ' ' or " " is a character.

Python Multiline Strings


Multiline strings are strings which extend upto multiple lines. These are enclosed within triple single quotes ''' ''' or triple double quotes """ """.

mystring = '''This is a multiline string
which is extended in two lines'''
print(mystring)
Output
This is a multiline string
which is extended in two lines
mystring = """This is a multiline string
    which is extended in two lines"""
print(mystring)
Output
This is a multiline string
    which is extended in two lines

Multiline strings can also be used as multiline comments or docstrings if not assigned to a variable. This is because if not assigned to a variable or not involved in any operation, these are not really doing anything in the code and hence get ignored. We already read about multiline comments in the chapter Basics of Python. We will be looking at docstrings in a separate chapter.

Python Accessing Characters from String


A particular character from a string can be accessed using its index. 

Just like lists, every character in a string has a unique index based on its position. Indices start from 0. Therefore, the first character of a string has index 0, the second character has index 1, and so on.

For example, consider the following string.

mystring = "Hey!"

In this string, the index of 'H' is 0, 'e' is 1, 'y' is 2 and '!' is 3. Thus, the index started from 0 and went up to 3.

charcter 'H' 'e' 'y' '!'
index 0 1 2 3

A character of a string can be accessed by writing name_of_string[index], where index is the index of the character in the string.

Therefore, the 2nd character of the string mystring can be accessed by writing mystring[1] (because the index of the 2nd character is 1).

mystring = "Hey!"
print(mystring[0])
print(mystring[1])
print(mystring[2])
print(mystring[3])
Output
H
e
y
!

Python Negative Index


Just like lists, in strings also we can access a character by using a negative index.

The last character of a string has index -1, second last character has index -2, and so on.

mystring = "Hey!"
 
#accessing using indices
print(mystring[0])
print(mystring[1])
print(mystring[2])
print(mystring[3]) 
 
# accessing using negative indices
print(mystring[-1])
print(mystring[-2])
print(mystring[-3])
print(mystring[-4])
Output
H
e
y
!
!
y
e
H

Here, mystring[-1] returns the last character ‘!’ of the string mystring, mystring[-2] returns the second last character ‘y’, and so on.

Python String Slicing


A range of characters from a string can be accessed using the slicing operator :.

To access characters from the ith index to the jth index of a string, we write name_of_string[i:j+1].

mystring = "Python@Codesdope"
print(mystring[2:6])
Output
thon

mystring[2:6] returned the characters from the 2nd index to the 5th index i.e., 'thon'.

To access the characters from index 4 till the end of a string, use name_of_string[4:].

To access the characters from the start till index 4 of a string, use name_of_string[:5].

To access all the characters from the start till the end of a string, use name_of_string[:].

mystring = "Python@Codesdope"
 
# from 2nd character till 5th character
print(mystring[1:5])
 
# from start till 5th character
print(mystring[:5])
 
# from 5th character till end
print(mystring[4:])
 
# from start till 3rd last character
print(mystring[:-2])
 
# from 4th last character till 3rd last character
print(mystring[-4:-2])
 
# from 3rd character till 3rd last character
print(mystring[2:-2])
 
# all characters
print(mystring[:])
Output
ytho
Pytho
on@Codesdope
Python@Codesdo
do
thon@Codesdo
Python@Codesdope

We can also give a step to the slice to skip some number of characters while slicing.

Look at the following example.

mystring = "Python@Codesdope"
 
# from 2nd character till 9th character
print(mystring[1:9])
 
# from 2nd character till 9th character in step 2
print(mystring[1:9:2])
 
# from 2nd character till 9th character in step 3
print(mystring[1:9:3])
Output
ython@Co
yhnC
yoC

mystring[1:9] returned the characters from the 1st index till the 8th index.

mystring[1:9:2] also returned the characters from the 1st index till the 8th index, but it returned every 2nd character after the character having the start index.

mystring[1:9:3] also returned the characters from the 1st index till the 8th index, but it returned every 3rd character after the character having the start index.

mystring = "Python@Codesdope"
 
# from 3rd character till 9th character
print(mystring[2:9])
 
# from 3rd character till 9th character in step 2
print(mystring[2:9:2])
 
# from 3rd character till 9th character in step 3
print(mystring[2:9:3])
 
# from start till 9th character in step 2
print(mystring[:9:2])
 
# from 3rd character till end in step 3
print(mystring[2::3])
 
# characters from start till end in step 2
print(mystring[::2])
Output
thon@Co
to@o
tno
Pto@o
tnosp
Pto@oedp

Giving a negative step will return the characters of a string in the reverse order. A step of -1 returns the reversed string.

mystring = "Python@Codesdope"
 
# reversed string
print(mystring[::-1])
 
# reversed string with step -2
print(mystring[::-2])
Output
epodsedoC@nohtyP
eosdCnhy

Python Changing Characters of String


Strings are immutable, which means that the characters of a string can’t be changed. However, a new string value can be assigned to the same variable.

Let’s try to change a single element of a string.

mystring = "Python@Codesdope"
mystring[6] = "a"
Output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

We tried to change the 7th character of a string and got an error.

Now, let’s assign a new string to the variable mystring.

mystring = "Python@Codesdope"
mystring = "Java@Codesdope"
print(mystring)
Output
Java@Codesdope

Python Deleting String


We cannot delete characters from a string, Instead, we can delete an entire string using the del keyword.

mystring = "Python@Codesdope"
del mystring[6]
Output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion

We tried to delete the 7th character of a string and got an error.

mystring = "Python@Codesdope"
del mystring
print(mystring)  # printing the string after deleting it
Output
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'mystring' is not defined

We deleted the entire string mystring. Thus, we got an error on printing the string after deleting it.

Python String Operations


Python String Concatenation (+)


Two or more strings can be concatenated or combined using the + operator.

string1 = "Codes"
string2 = "Dope"
string3 = string1 + string2
print(string3)
Output
CodesDope

string1 and string2 are concatenated to form string3.

Python String Repetition (*)


A string can be repeated a specified number of times using the * operator.

string1 = "Python"
string2 = string1 * 3
print(string2)
Output
PythonPythonPython

string1 is repeated 3 times to form string2.

Python String Membership Test


We can test if a character is present in a string using the membership operators in and not in.

mystring = "Ice and candy"
print("e an" in mystring)
print("ice" in mystring)
print("candy" not in mystring)
Output
True
False
False

Python String Comparison


Two strings can be compared using Relational Operators. Strings are compared character by character, and these characters are compared lexicographically i.e. based on their ASCII values. The character having the lower Unicode value is considered smaller. You can find the ASCII values for different characters here.

string1 = "Candy"
string2 = "Candy"

print(string1 == string2)
print(string1 != string2)
print(string1 > string2)
print(string1 < string2)
print(string1 >= string2)
print(string1 <= string2)
Output
True
False
False
False
True
True

The values of both the strings are same i.e., "Candy".

string1 = "Hat"
string2 = "Heat"

print(string1 == string2)
print(string1 != string2)
print(string1 > string2)
print(string1 < string2)
print(string1 >= string2)
print(string1 <= string2)
Output
False
True
False
True
False
True

Here the strings "Hat" and "Heat" are compared. To start with, the ASCII values of the first characters of both the strings are compared. Since that is equal, the ASCII values of the second characters of the strings are then compared. The ASCII value of ‘a’ (97) is smaller than that of ‘e’ (101), and therefore the string "Hat" is smaller than "Heat" lexicographically.

Looking at the ASCII chart, we can see that the ASCII values of uppercase alphabets (65 - 90) are smaller than those of lowercase alphabets (97 - 122). Therefore, the comparisons are case-sensitive.

string1 = "Hat"
string2 = "hat"

print(string1 == string2)
print(string1 != string2)
print(string1 > string2)
print(string1 < string2)
Output
False
True
False
True

"Hat" is smaller than "hat" because the ASCII value of ‘H’ is smaller than that of ‘h’.

Python does not handle uppercase and lowercase letters the same way that people do. All the uppercase letters come before all the lowercase letters.

Python Iteration Through a String


Iteration through a string is done in the same way we iterate through a list because string is also a list in which each element is a character.

mystring = "CodesDope"
for ch in mystring:
    print(ch)
Output
C
o
d
e
s
D
o
p
e

A variable ch goes to each element in the string mystring and takes its value, and that value is printed on the screen.

We can also iterate through a string using another way.

mystring = "Hey"
for i in range(len(mystring)):
    print(mystring[i])
Output
H
e
y

len() function is used to return the number of characters in a string. Therefore range(len(mystring)) is equal to range(3). This means that there will be three iterations in the loop. You must have understood the rest of the code.

Using Quotes in Python String


Suppose we have a string "This is "Python" course". This string contains another set of double quotes inside it. Let’s try to print it.

mystring = "This is "Python" course"
print(mystring)
Output
File "", line 1
    mystring = "This is "Python" course"
                         ^
SyntaxError: invalid syntax

We got a syntax error. This is because we cannot nest the same type of quotes with which we enclose the string.

To prevent this, there are two solutions.

In the first solution, follow the rule that if a string contains double quotes, then enclose it within single quotes, and if it contains single quotes, then enclose it within double quotes. Thus, the strings 'This is "Python" course' and "This is 'Python' course" will give no syntax errors.

mystring = 'This is "Python" course'
print(mystring)
Output
This is "Python" course
mystring = "This is 'Python' course"
print(mystring)
Output
This is 'Python' course

The other solution is to use \' and \" in place of ' and " respectively in the string. \' and \" are escape sequences which we will look at in the next section.

mystring = "This is \"Python\" course"
print(mystring)
Output
This is "Python" course

Python Escape Sequence


An escape sequence starts with an escape character (backslash \) and is followed by a special character (characters having special meaning in Python like ', '', etc). The escape sequences supported by Python get interpreted when placed inside a string.

For example, \' and \" are two escape sequences which tell Python that ' and " are not the special string opening and closing quotes and just simple ‘ and “ characters. We have seen an example of these two escape sequences in the previous section.

The list of escape sequences supported by Python are given below.

Escape Sequence Description
\\ Backslash (\)
\' Single Quote (')
\" Double Quote (")
\a ASCII Bell
\b ASCII Backspace
\f ASCII Form Feed
\n ASCII Line Feed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\uxxxx Character with 16-bit hex value xxxx (Unicode only)
\Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (Unicode only)
\ooo Character with octal value ooo
print("C:\\Documents\\Folder")
print("This is \'Python\' course")
print("This is \"Python\" course")
print("First line\nSecond line")
print("Before horizontal tab\tAfter horizontal tab")
print("Before horizontal tab\t\tAfter two horizontal tabs")
Output
C:\Documents\Folder
This is 'Python' course
This is "Python" course
First line
Second line
Before horizontal tab    After horizontal tab
Before horizontal tab        After two horizontal tabs

\\ gets replaced by \, \' gets replaced by ', \" gets replaced by ", \n inserts a new line and \t inserts a horizontal tab.

\n


\n or new line character is a special character which we frequently use. As stated above it is used to print a new line. Let’s look at some examples of it.

print("ab\ncde")
print("Hello\n\n\n\nCodesDope")
print("Hello Codes\nDope")
print("Hello World")
Output
ab
cde
Hello



CodesDope
Hello Codes
Dope
Hello World

Python Ignoring Escape Sequence


The meaning of escape sequences inside a string can be ignored and these can be displayed as part of the string by adding r or R before the string.

print(r"C:\\Documents\\Folder")
print(R"This is \'Python\' course")
Output
C:\\Documents\\Folder
This is \'Python\' course

In this example, we can see that \\ didn’t get replaced by \ and \' didn’t get replaced by '.

Creating List from String in Python


A string can be converted into a list using the following functions.

list()


With the list() function, each character of a given string becomes an element of the list.

mystring = "Codesdope"
mylist = list(mystring)
print(mylist)
Output
['C', 'o', 'd', 'e', 's', 'd', 'o', 'p', 'e']

split()


The split() function breaks a given string into multiple substrings at the specified separator and returns a list having these substrings as its elements.

Let’s look at an example.

mystring = "Have a good day"
print(mystring.split(" "))
Output
['Have', 'a', 'good', 'day']

In mystring.split(" "), the separator is space " ". Therefore, the string got splitted at the spaces " " giving four substrings 'Have', 'a', 'good' and 'day', and a list is returned containing the substrings as elements.

The syntax of split is:

str.split(separator, maxsplit)

separator - The string gets split at the specified separator. This is also called a delimiter. Its default value is whitespace (space, newline, etc.).

maxsplit - This specifies the number of times the string is split at the separator. Its default value is -1 (which means that the string is split at every occurrence of the separator).

Let’s take another example where comma is used as a separator.

mystring = "Apples, Oranges, Grapes, Watermelons"
print(mystring.split(", "))
Output
['Apples', 'Oranges', 'Grapes', 'Watermelons']

Here, ", " is used as the separator.

If no separator is specified, then by default any whitespace (space, newline, etc.) becomes the separator.

mystring = "Have a good day"
print(mystring.split())
Output
['Have', 'a', 'good', 'day']

In the above example, no separator was passed to the split() function, and so by default the string got splitted into substrings at the spaces.

A second value (maxsplit) can be passed to the split() function to specify the number of times a given string is split at the specified separator. If this value is 1, then the string gets splitted into two substrings at the leftmost separator. If the value is 2, then the string gets splitted into three substrings at the leftmost and the second left separators.

mystring = "Python.Java.C.Perl.C#.Ruby"

print(mystring.split(".", 1))  # maxsplit = 1
print(mystring.split(".", 2))  # maxsplit = 2
print(mystring.split(".", 3))  # maxsplit = 3
print(mystring.split(".", 0))  # maxsplit = 0
print(mystring.split("."))  # no maxsplit
Output
['Python', 'Java.C.Perl.C#.Ruby']
['Python', 'Java', 'C.Perl.C#.Ruby']
['Python', 'Java', 'C', 'Perl.C#.Ruby']
['Python.Java.C.Perl.C#.Ruby']
['Python', 'Java', 'C', 'Perl', 'C#', 'Ruby']

In this example, when the maxsplit value is 1, then the string gets split at the leftmost separator . into two substrings i.e., ‘Python’ and ‘Java.C.Perl.C#.Ruby’. When the maxsplit value is 2, it gets split at the two leftmost separators . into three substrings i.e., 'Python', 'Java', and 'C.Perl.C#.Ruby'. When the maxsplit value is 0, then the string doesn’t get split. When no maxsplit is passed, then it gets split at every separator.

rsplit()


The rsplit() function breaks a given string into multiple substrings at the specified separator from the right and returns a list having these substrings as its elements. The only difference from split() is that split() splits from the left while rsplit() splits from the right.

Syntax

str.rsplit(separator, maxsplit)

separator - The string gets split at the specified separator from the right. This is also called a delimiter. Its default value is whitespace (space, newline, etc.).

maxsplit - This specifies the number of times the string is split at the separator. Its default value is -1 (which means that the string is split at every occurrence of the separator).

Example

If maxsplit is not passed, rsplit() gives the same result as split().

mystring = "Apples, Oranges, Grapes, Watermelons"
print(mystring.rsplit(", "))
print(mystring.rsplit())
Output
['Apples', 'Oranges', 'Grapes', 'Watermelons']
['Apples,', 'Oranges,', 'Grapes,', 'Watermelons']

If maxsplit is passed, it specifies the number of times a given string is split at the specified separator from the right.

mystring = "Python.Java.C.Perl.C#.Ruby"

print(mystring.rsplit(".", 1))  # maxsplit = 1
print(mystring.rsplit(".", 2))  # maxsplit = 2
print(mystring.rsplit(".", 3))  # maxsplit = 3
print(mystring.rsplit(".", 0))  # maxsplit = 0
print(mystring.rsplit("."))  # no maxsplit
Output
['Python.Java.C.Perl.C#', 'Ruby']
['Python.Java.C.Perl', 'C#', 'Ruby']
['Python.Java.C', 'Perl', 'C#', 'Ruby']
['Python.Java.C.Perl.C#.Ruby']
['Python', 'Java', 'C', 'Perl', 'C#', 'Ruby']

splitlines()


The splitlines() function splits a given string into multiple substrings at line breaks and returns a list having these substrings as its elements.

string1 = "Hello learners, Welcome to the Python course."
print(string1.splitlines())

string2 = '''Hello learners,
Welcome to the Python course.'''
print(string2.splitlines())
Output
['Hello learners, Welcome to the Python course.']
['Hello learners,', 'Welcome to the Python course.']

string1 has no line break, therefore the list returned by the splitlines() function has only one element which is the string itself.

string2 is a multiline string which has a line break. As a result, it gets split into two substrings at the line break and the returned list contains these two substrings as its elements.

Line breaks in a string are also induced by various escape characters like \n and \r. \n is called the newline character which breaks the string when printed.

mystring = "Hello learners,\nWelcome to the Python course."
print(mystring)
print(mystring.splitlines())
Output
Hello learners,
Welcome to the Python course.
['Hello learners,', 'Welcome to the Python course.']

Here, we have first printed the string mystring to show you how printing \n breaks the line. Therefore, splitlines() splits the string into two substrings at the line break \n.

Built-in Functions in Python


Python len()


It returns the number of characters in a string.

mystring = "Hello learners"
print(len(mystring))
Output
14

Common Python String Functions


We have already looked at some of the string functions like split(), rsplit(), splitlines(), remove(), pop(), clear() and copy(). Other useful functions are shown below.

Python capitalize()


It returns a string with the first character in uppercase and the other characters in lowercase. It doesn’t change the original string.

mystring = "hEy tHEre WOrld!"
new_string = mystring.capitalize()
print("Original string:", mystring) # printing original string
print("Updated string:", new_string) # printing updated string
Output
Original string: hEy tHEre WOrld!
Updated string: Hey there world!

Python lower()


It returns a string with all the characters in lowercase. It doesn’t change the original string.

mystring = "hEy tHEre WOrld!"
new_string = mystring.lower()
print("Original string:", mystring) # printing original string
print("Updated string:", new_string) # printing updated string
Output
Original string: hEy tHEre WOrld!
Updated string: hey there world!

Python upper()


It returns a string with all the characters in lowercase. It doesn’t change the original string.

mystring = "hEy tHEre WOrld!"
new_string = mystring.upper()
print("Original string:", mystring) # printing original string
print("Updated string:", new_string) # printing updated string
Output
Original string: hEy tHEre WOrld!
Updated string: HEY THERE WORLD!

Python swapcase()


It returns a string with the case of all the characters inverted, which means that all lowercase characters get converted to uppercase and vice versa. It doesn’t change the original string.

mystring = "hEy tHEre WOrld!"
new_string = mystring.swapcase()
print("Original string:", mystring) # printing original string
print("Updated string:", new_string) # printing updated string
Output
Original string: hEy tHEre WOrld!
Updated string: HeY TheRE woRLD!

Python title()


It returns a string with the first character of each in uppercase and the rest of the characters in lowercase. It doesn’t change the original string.

mystring = "hEy tHEre WOrld!"
new_string = mystring.title()
print("Original string:", mystring) # printing original string
print("Updated string:", new_string) # printing updated string
Output
Original string: hEy tHEre WOrld!
Updated string: Hey There World!

Python join()


It joins the element of a list to form a string.

mystring = ["hEy", "tHEre", "WOrld!"]
print(" ".join(mystring))
print(";".join(mystring))
Output
hEy tHEre WOrld!
hEy;tHEre;WOrld!

Python index()


It returns the index of the specified substring in a string.

mystring = "I am a programmer"
print(mystring.index("prog"))
Output
7

mystring.index("prog") returned the index of "prog" in the string mystring.

If the specified substring occurs more than once in a string, then the index of its first occurrence is returned as shown below.

mystring = "I am a programmer"
print(mystring.index("am"))
Output
2

In this example, the substring "am" occurs twice at indices 2 and 12, but only the index of its first occurrence is returned.

We can also pass the start index from which we want the search to begin and the end index upto which we want the search to take place.

mystring = "I am a programmer"
print(mystring.index("am", 6)) # "am" is searched after index 6
print(mystring.index("am", 1, 6)) # "am" is searched between index 1 and index 6
Output
12
2
mystring.index("am", 6) returned the index of "am" after index 6 (6 is the start index).

print(mystring.index("am", 1, 6)) returned the index of "am" between indices 1 and 6 (1 is the start index and 6 is the end index).

Python rindex()


It returns the highest index of the specified substring in a string. We can also pass the start index from which we want the search to begin and the end index upto which we want the search to take place.

mystring = "I am a programmer"
print(mystring.rindex("prog"))
print(mystring.rindex("am", 6)) # "am" is searched after index 6
print(mystring.rindex("am", 1, 6)) # "am" is searched between index 1 and index 6
Output
7
12
2

In the above example, using index() will give the same result.

In case of multiple occurrences of the specified substring in a string, then the index of its last occurrence is returned as shown below.

mystring = "I am a programmer"
print(mystring.rindex("am"))
Output
12

In this example, the substring "am" occurs twice at indices 2 and 12, but only the index of its last occurrence is returned.

Python replace()


It replaces a substring with another substring in a string.

mystring = "I am a programmer"
print(mystring.replace("am", "was"))
Output
I was a progrwasmer

In this example, both the occurrences of the substring "am" is replaced by another substring "was".

We can also pass a second value to the replace() function to specify the number of occurrences of the old substring to be replaced.

mystring = "I scream, you scream, we all scream for ice cream"
print(mystring.replace("scream", "cry"))  # all occurrences of scream get replaced
print(mystring.replace("scream", "cry", 2))  # first two occurrences of scream get replaced
Output
I cry, you cry, we all cry for ice cream
I cry, you cry, we all scream for ice cream

Python isalnum()


It returns True if all the characters of a given string are alphanumeric (either alphabets or numbers). Otherwise, it returns False.

string1 = "Abcd123dE"
string2 = "Abcd,123dE"  # contains a comma
string3 = "564782"

print("Is string1 alphanumeric?", string1.isalnum())
print("Is string2 alphanumeric?", string2.isalnum())
print("Is string3 alphanumeric?", string3.isalnum())
Output
Is string1 alphanumeric? True
Is string2 alphanumeric? False
Is string3 alphanumeric? True

Python isalpha()


It returns True if all the characters of a given string are alphabets. Otherwise, it returns False.

string1 = "AbcdEf"
string2 = "Abcd 123dE"  # contains a space
string3 = "Abcd123dE"  # contains numbers

print("Does string1 contain only alphabets?", string1.isalpha())
print("Does string2 contain only alphabets?", string2.isalpha())
print("Does string3 contain only alphabets?", string3.isalpha())
Output
Does string1 contain only alphabets? True
Does string2 contain only alphabets? False
Does string3 contain only alphabets? False

Python isdigit()


It returns True if all the characters of a given string are digits. Otherwise, it returns False.

string1 = "2274645"
string2 = "Abcd123dE"  # contains alphabets

print("Does string1 contain only digits?", string1.isdigit())
print("Does string2 contain only digits?", string2.isdigit())
Output
Does string1 contain only digits? True
Does string2 contain only digits? False

Python islower()


It returns True if all the alphabets of a given string are in lowercase. Otherwise, it returns False.

string1 = "codesdope"
string2 = "CodesDope"

print("Is string1 in lowercase?", string1.islower())
print("Is string2 in lowercase?", string2.islower())
Output
Is string1 in lowercase? True
Is string2 in lowercase? False

Python isupper()


It returns True if all the alphabets of a given string are in uppercase. Otherwise, it returns False.

string1 = "CODESDOPE"
string2 = "CodesDope"

print("Is string1 in uppercase?", string1.isupper())
print("Is string2 in uppercase?", string2.isupper())
Output
Is string1 in uppercase? True
Is string2 in uppercase? False

Python istitle()


It returns True if the string is in titlecase. Otherwise, it returns False.

string1 = "Hey There World!"
string2 = "Hey there world!"

print("Is string1 in titlecase?", string1.istitle())
print("Is string2 in titlecase?", string2.istitle())
Output
Is string1 in titlecase? True
Is string2 in titlecase? False

You have seen many useful things to do with string in this chapter. But there are a lot more functions to explore. You can use them whenever you need them from the official documentation.

Don't spend so much time trying to choose the perfect opportunity that you miss the right opportunity.
- Michael Dell


Download Our App.
BlogsDope App
Get it on Google Play
Ask Yours
Post Yours
Doubt? Ask question