Python String Exercises

Let’s check out some exercises that will help you understand Python strings better.

Exercise 9-a

Assign the string below to the variable in the exercise.


"It's always darkest before dawn."


All you need to do is make sure your string is inside quotation marks.

str = "It's always darkest before dawn."

Exercise 9-b

By using first, second and last characters of the string, create a new string.


You can add strings by using (+) character.

ans_1 = str[0]+str[1]+str[-1]

Exercise 9-c

Replace the (.) with (!)


You can’t directly change a string, because they’re immutable. But you can use .replace() method and assign a new string to the same variable.

.replace() will take two arguments, first: value to replace, second: new value.

str = str.replace(".", "!")

Exercise 9-d

Reassign str so that, all its characters are lowercase.


.lower() method will create a version of your string with all lowercase characters.

str = str.lower()

Exercise 9-e

Now make everything uppercase.


.upper() method will create a version of your string with all uppercase characters.

str = str.upper()

Exercise 9-f

Make the string so that everything is properly and first letter is capital with one function.


.capitalize() will make the first letter uppercase and everything else lowercase.

str = str.capitalize()

Exercise 9-g

Does the string start with an A?


Assign a boolean answer to the ans_1 variable.


.startswith() method checks if the first letter of the string is a certain character or not. It returns True or False.

ans_1 = str.startswith("A")

Exercise 9-h

Does it end with a fullstop (.) ?


.endswith() will check the last character of a string.

ans_1 = str.endswith(".")

Exercise 9-i

Using .index() method, identify the index of character: (v).


.index() method helps you identify the index of a substring.

ans_1 = str.index("v")

Exercise 9-j

Using .find() method, identify the index of character: (m).


.find() method also helps you identify the index of a substring.

ans_1 = str.find("m")

Exercise 9-k

Try to see what results you get looking for character: (X). First with .find() method and then with .index() method.


.find() method returns -1, when it can’t find a character while .index() method returns a ValueError.

ans_1 = str.find("X")

Exercise 9-l

Which character occur more often in the string? "a" or "o" ? Print both counts inside the print function.


.count() method tells how many times character(s) occur in a string. You need to type the value you’re checking inside .count()

ans_1 = str.count("a")

ans_2 = str.count("o")

Exercise 9-m

Print the types of two given variables with the print function.


You can use type() function with strings and many other types of data.

ans_1=type(v_1)

ans_2=type(v_2)

Exercise 9-n

What is the length of the given string?


len() function will give you the character length of your string.

ans_1 = len(str)