top of page
top

Python 9a - String Handling

noun-text-4214022-FFFFFF.png

What is String Handling?

String handling refers to the manipulation of a string variable, typical uses include:

​

  • Checking the length of a variable.

  • Searching a variable for a certain phrase.

  • Checking the number of times a specific character or word is used.

​

String handling is used to examine passwords and to ensure that they are of an acceptable strength (e.g. by checking that they are at least 8 characters in length and include a mixture of capital letters, lowercase letters and symbols).

Password:

arsenal

Password:

$tr0nG_pA$$w0rd

Lowercase & Uppercase

.lower() and .upper() are functions that convert a string into a fully lowercase or uppercase version.

dogbreed = "Chihuahua"
print(dogbreed.upper())

CHIHUAHUA

character = "sPoNgeBoB"
print(character.lower())

spongebob

You may have realised that Python is very specific. 'yes', 'Yes' and 'YES' are all treated as different values

​

Converting user input into one case, such as lowercase, and then comparing that input is a better way of checking an input than having an if statement with multiple or comparisons.

 

The program below converts the user input into lowercase to compare. 'yes', 'Yes' and 'YES' are all converted to 'yes'. 

answer = input("Would you like water? ")
answer = answer.lower()

if answer == "yes":
    
print("I'll fetch you a glass.")
else:
    
print("Don't dehydrate!")

Would you like water? yes

I'll fetch you a glass.

Would you like water? Yes

I'll fetch you a glass.

Would you like water? YES

I'll fetch you a glass.

Practice Task 1

Ask the user to enter their first name and surname. Print their surname in uppercase followed by their first name in lowercase.

Example solution:

Enter First Name: Jayden

Enter Surname: Hargrove

Welcome HARGROVE, jayden

Count Characters

The easiest way to count how many times a certain value appears within a string is to use the .count() command.

 

It is important to note that, just like when using an input statement or calculation line, you must save the calculation into a variable.

 

An example, for counting the number of e’s in a sentence, is below:

sentence = input("Enter your sentence: ")


e_count = sentence.count("e")
 

print("There were", e_count, "e's in your sentence!")

Enter your sentence: even ellie eats elderberries

There were 9 e's in your sentence!

Practice Task 2

Create a program that counts how many instances of the letter a have been entered in a sentence.

Bonus: Use the .lower() function in your code to include capital letters.

Example solution:

Enter a sentence: An angry aardvark named Aaron.

That sentence had 8 a's.

Finding the Length of a String

Just like when we wanted to find the length of a list, we use the len command to see how many characters are in a string.

 

It is sensible to save the result of the function into a variable so it can be used later.

fruit = input("Enter a fruit: ")

length = len(fruit)

print("That fruit was", length, "characters.")

Enter a fruit: pineapple

That fruit was 9 characters.

A common reason for finding the length is as part of validation, for example, checking a password is more than 8 characters:

password = input("Enter a new password: ")

length = len(password)

if length >= 8:

    print("Password accepted!")

else:

    print("Password is too short, must be at least 8 characters.")

Enter a password: snake54

Password is too short, must be at least 8 characters.

Enter a password: pebblesthedog76

Password accepted!

Practice Task 3

Create a program that asks for a name. Check that the name is between 4 and 10 characters. Print appropriate messages if it is within this range and if it isn't.

Example solution:

Enter a name: Tom

That name is too short, it must be between 4 and 10 characters.

Checking the Start / End of a String

To determine if the first character in a string is a specific value use the .startswith() command.

​

.startswith() is a function that will return True or False.

​

Below is an example program to check if a name begins with the letter L.

name = input("Enter a name: ")
if name.startswith("L") == True:
 
print("I like that name.")
else:
 
print("I don't like that name.")

Enter a name: Lionel

I like that name.

Enter a name: Katjaa

I don't like that name.

Similarly, you can use .endswith() to check the last characters of a string.

Practice Task 4

Ask the user to enter a country. Print a message if it ends with 'land', 'stan' or any other ending. Use .endswith()

Example solution:

Enter a country: Finland

You have entered a 'land' country. There are 9 in the world.

Enter a country: Kyrgyzstan

You have entered a 'stan' country. There are 7 in the world.

Enter a country: Peru

Thanks for your entry.

Note: You don't need to check if it's a valid country.

Reversing a String

To reverse a string, you write the variable name and then use square brackets to move one character at a time backwards.

 

The first two colons are left empty as they denote where to start and end from (which don’t need to be changed).

​

Therefore the -1 states that it will reverse from the end to the start:

string14.png
string15.png

Ask the user to enter a random sentence.

​

Print the sentence in reverse.

Example solution:

py189.PNG

Practice Task 5

Printing Parts of a String

You may want to print just part of a string or variable using square brackets.

 

You can also use len to work out the length and work back, if you want to display the last characters:

string16.png
string17.png

Practice Task 6

Ask the user to input a long word.

​

Output the middle character of the word.

Example solution:

py190.PNG

Split Strings

Use the .split command to split a string into separate words.

​

An empty split command such as words.split() will split at each space.

split1.png
split2.png

You can enter a value in the brackets to split at certain characters, such as words.split(",")

split5.png
split6.png

Use the len function to count the number of words once they have been split.

spit3.png
split4.png

You can use a for loop to cycle through each word. The program below checks the length of each word.

split7.png
split8.png

Practice Task 7

Ask the user to input a sentence.

​

Calculate and print the amount of words in the sentence.

​

Calculate and print the amount of words that begin with s.

Example solution:

split9.png
bottom of page