This is the second and final part to my strings in python tutorial. In this part, I will cover things like formatting strings, joining strings, getting strings from a list and searching strings.
Python has a built in system for some basic formatting of strings. When you are using print statements, you can use the \ character followed by a letter to do something to the string. The ones I will talk about today are \n - starts a new line and \t - moves the text after it to the next tab point. The \n can be useful if you want to print something on another line without making another print statement.
print 'line 1\nline 2'
Python picks up the \n in the string and moves the text after it to the next line. If you want to use the \ at the end of a string, you have to do it twice because one is automatically removed from the string. e.g.
print 'Test 1: \' print 'Test 2: \\'
In test one, if you have characters after the \ it will accept it. So,
'Test 1: \ 123' would be accepted and it would print the \.
The \t code is used for aligning you text. After you use a \t the text after it will start from the next tab point. Try the following example:
print 'abc\tdef\tghi\tjkl' print 'a\tb\tc\td' print 'abcdefghi\tjklmnop'
After you run the example, you should notice that if (like in the last print statement) your text before \t takes up more than one tab space, it will go to the next one along. \t is handy when you need to print some tables that need to lined up in the interactive editor. You can also use more than one \ code in one print statement.
print 'Hello\nWorld\tNew tab.'Sometimes you will want to change the case of a string or remove parts of the string. Using the string module once again, you can do these things. If you want to change the case of a string (good for comparing things) you can use the .upper() or .lower() for all the characters to be changed to upper case or to lower case. This is good for comparing two strings so the user can enter in any case and you can change it to a single case. Another one (and my favourite) is capitalize (). What this does is change all of the letters to lowercase except the first letter, which will become a capital letter. These are neat ways of case-proofing user entered strings. Take a look at the example below:
cap_str = 'HELLO WORLD' print cap_str.lower() low_str = 'hello world' print low_str.upper() print low_str.capitalize()
So, if you entered in a string that way HeLlO WorLD, by using one of these functions you could still compare it to another predefined string such as Hello world. While I am talking about comparing strings, another thing you will often use is the strip() function. This will strip what you specify from the string. In the way of comparing, you often want to remove unnecessary spaces from the end of a string. Sometimes you need to remove the \n or \t from a string. So, just call the function and pass it what you want you want removed from the string. Try this code:
string = 'remove the letters re' newString = string.strip('re') print newString spaces = 'hello ' newSpaces = spaces.strip(' ') print newSpaces sameLetter = 'abababababab' NewsameLetter = sameLetter.strip('ab') print NewsameLetter
You should notice that the last print only prints out spaces. This is because we have removed all of the ab's from the string, which was all ab's.
Joining strings and getting strings from lists
Just in case you are new to lists, I will briefly explain them. Lists can be used to hold just about any type of data in python. They hold them in a certain order and you can modify lists as well. For more information, you should see one of the tutorials in the python section.
Anyway, the way you retrieve items from a list is by using an index position. The index position tells python which item in the list you want. You use the index by putting it after the list name in these .
So, if you have a list like this:
list = ['one', 'two', 'three', 'four', 'five']
You could print number two by using this:
Remember! Computers start counting at 0. This means that 1 is our equivalent to two (if that makes sense). So when I told python to print list, it will print two. So, that's how you retrieve a string from a list. You just state it's index position.
list = ['one', 'two', 'three', 'four', 'five'] for i in range(5): num = int(i) print 'number: ', list[num]The code in the example take an item from the list and prints it.
Sometimes you will want to split and join strings. This can be useful if say in a program someone enters in their name and you want to search for their last name only. So how would you do that? Well, you split the string at a certain character which will create a list containing both strings. You can then grab each string from the list (as shown above) and search for it. So to split a string, we use the .split() function. This is a function from the string module (built into python).So, lets try splitting a string. When we call the split function, we give it the character we want to split at as an argument. See the example below for more help.
name = 'Jane Doe' name_split = name.split(' ')#passing the space as the place to split print name_split First_Name = name_split print 'First Name: '+First_Name Last_Name = name_split print 'Last Name: '+Last_Name
When you run the code, you should get the output: First Name: Jane
Last Name: Doe
So, now to join the string. Depending on what you are trying to join (a list or two separate strings), it is different. If you are trying to join to separate strings, you can just use the + I talked about in the first tutorial e.g. (continuing on from last example)
Full_Name = First_Name+' '+Last_Name print Full_NameWhen you print this, you should get the original string that we had to split before. If you are trying to join all of the items is list, you can do this:
list = ['Hello', 'my', 'name', 'is', 'John'] string = ' '.join(list) print string
When you see the string, you might have noticed that there are spaces between all of the words. This is because when we used the join function, we used ' '.join. This space we used fist tells python what to put where the strings are joined. Try using 'a'.join(list) and see what happens.
When it comes to searching strings, there are a few things you can do to check certain parts of strings to the whole string. Using the string module, (you don't have to import it) you can use the functions .startswith() and .endswith() to check what a string starts with and ends with. In the brackets, you pass it what you want to check that it starts/ends with. If it does start/end with what you passed it, it returns True. If it doesn't, it returns False. So lets try that out.
name = 'Jane' checkStart = name.startswith('J') print checkStart checkStart = name.startswith('Jan') print checkStart checkStart = name.startswith('F') print checkStart checkEnd = name.endswith('e') print checkEnd checkEnd = name.endswith('ne') print checkEnd checkEnd = name.endswith('s') print checkEnd
When you run the code, you should get True, True, False, True, True, False. So, you have searched the start and end of the string to see if it ends or starts with what you want. If you want to search anywhere in a string, you need to use in and index. If you want to check if your search is in in the string, just use
if search in string:. You can then find exactly where it is by using the index(). Before I give you an example in code, I just want to explain the index. When you use index, it will give you a position. This is how many letters along the start of the word is. e.g. If you have the string 'Hello World' and you are searching for the word World, when you use index you will get 6. This means that the W of world is 6 characters (including spaces) along.
So, working with my name search example, the search might go like this if you are looking to find the last name of the person.
name = 'Jane Doe' if 'Doe' in name: position = name.index('Doe') print 'Doe is at position ', positionJust remember computers start at 0! This often still tricks me when I am working with loops and things like positions.
So, lets put all of this searching, splitting, joining and formatting to use and make a basic name searching system.
names = 'Jane,John,Alex,Jessica' lastNames = 'Doe,Doe,Mannequin,Doll' search = raw_input('Enter in a name to search for:\n') search_cap = search.capitalize() nameOriginal = search_cap.split(' ') First_nameOriginal = nameOriginal First_name = First_nameOriginal.strip(' ') print First_name if First_name in names: position = names.index(First_name) if position == 0: print 'We have found Jane Doe.(You searched for %s)' %search elif position == 5: print 'We have found John Doe.(You searched for %s)' %search elif position == 10: print 'We have found Alex Mannequin.(You searched for %s)' %search else: print 'We have found Jessica Doll.(You searched for %s)' %search else: print 'Sorry, the name '+search+' was not found!\nTry again next time'
The above code is just to demonstrate using some of the techniques I have talked about in this tutorial.
Good luck and happy programming!