String variables (text)
Suppose we want to print some kind of text message to the user? We can print text very easily, just start and end the text with a set of quotations. For instance
print( "Hello world")
Just as we can use variables to store numbers, we can also use them to store text.
name = "Mr Baumgarten" print( name )
Also just as we can add numbers together, we can add these text variables together too! Obviously there is no calculation involved, instead what happens is it joins the two bits of text together.
name = "Mr Baumgarten" message = "Hello " print( message + name )
If we change the value of the text variables, Python will reflect the change next time you perform the calculation.
name = "Mr Baumgarten" message = "Hello " print( message + name ) name = "Luke Skywalker" print( message + name )
Variables that contain a bit of text for their value are known in the programming world as STRINGS. We use quotation marks so Python knows where we start and end our text we want it to remember.
Getting the length of a string
It can be handy to get the length of a string. Python gives us a very useful command for this called
len() command will give us a number indicating how many characters are in our text string.
name = "Mr Baumgarten" length = len(name) print( length ) name = "Mr B" print( len(name) )
Multiplying strings together
Occasionally we might find it useful to multiply strings together. What does this do?
fish = "tuna" print( fish * 5 )
Don’t know when you’d ever use it, but nice to know about :-)
Extracting sub strings
Because strings are just text, they can get quite long. We might want to separate it into parts to be more useful. For instance, what happens if a string contains both the first and family names of someone? Or if a string contains someones date of birth and we need to calculate their age? How can we split it up into parts?
To extract parts of a string we use a set of square brackets after our variable name.
name = "Luke Skywalker" print( name[5:] ) print( name[5:8] ) print( name[:4] )
What are these doing?
name[5:]means get from after the 5th character up to the end
name[5:8]means get from after the 5th character up to the 8th character
name[:4]means get from the beginning, up to the 4th character
The general rule is:
new_string = old_string[ after_this_position : up_to_this_position ]
Another example: What will each of the following print?
s = "To infinity and beyond!" print( s[3:11] ) print( s[:5] ) print( s[5:] ) print( s[-7:] )
What if I want Python to automatically split a string containing a name into the given name and family name? While the above method will allow us to get parts of a string, we need a way to find where the space is before we can automate it.
To do this, Python gives us the
.index() command. To search for a space, we’d use it like this:
name = "Luke Skywalker" if space in name: space = name.index(" ") print( "The space is located at:",space )
What value will be printed from the above?
Notice that it didn’t give you the number 5 which is what you might have expected. It actually gives you the number of characters that appear before what you have searched for. (It’s actually a bit more technical than that, but not relevant for you at this beginning stage)
Regardless, we now have a numeric variable that tells us the location of the space. We can combine that with the square bracket notation to isolate the parts of the string that contain the given name and family name.
See if this example makes sense:
name = "Luke Skywalker" space = name.index(" ") given_name = name[:space] family_name = name[space+1:] print("Your given name is "+given_name) print("Your family name is "+family_name)
Other string functions
Some of the other cool things you can do with strings…
Replacing parts of a string
s = "To infinity and beyond!" print( s.replace(" ", "+") ) # To+infinity+and+beyond!
Counting occurances within a string
s = "To infinity and beyond!" print( s.count("i") ) ## 3
Changing case of text
s = "To infinity and beyond!" s.lower() ## to infinity and beyond! s.upper() ## TO INFINITY AND BEYOND! s.title() ## To Infinity And Beyond! s.swapcase() ## tO INFINITY AND BEYOND!
Query content of a string
s = "To infinity and beyond!" if s.isnumeric(): ## does it contain only numbers? if s.isalpha(): ## does it contain only letters? if s.islower(): ## is it all lowercase? if s.isupper(): ## is it all uppercase? if s.istitle(): ## is it all title case? if s.isspace(): ## is it all spaces?
Padding a string
s = "To infinity and beyond!" s.ljust(30) ## "To infinity and beyond! " s.rjust(30) ## " To infinity and beyond!"
For any string that consists of exactly two words with one space separating them, swap the two words around. For example: If the string
s="Hello world!", have the program print
Given a string, cut it into two equal parts. If the length of the string is odd, leave the middle character within the first chunk, so that the first string contains one more character than the second. Now print a new string on a single row with the first and second halves swapped: second half first and the first half last. (Can you solve it without using if?) For example, given the input
Given a string that may contain a letter f. Print the index of the first and last occurrence of f. If the letter f occurs only once, then output its index once. If the letter f does not occur, print -1. For example,
1 2; and
Remove string fragment. Given a string in which the letter h occurs at least twice. Remove from that string the first and the last occurrence of the letter h, as well as all the characters between them. For example, given
In the hole in the ground there lived a hobbit, output
Given a string. Replace in this string all the numbers 1 by the word one. For example
1+1=2should be replaced with
Given a string, delete all the characters @ from this string. For example