Chapter 2 Lab Exercise
7.2 Splitting and Joining Strings
While working with strings, you might come across issues where you have to organize, merge, or clean up certain text. As already mentioned, these tasks are part of the
string formatting processes in Python. Splitting and joining strings are very important processes of string formatting. Simply
enough, there are two methods that split and join strings, the split() method and the join() method, respectively.
Sometimes you might write programs that deal with file handling such as opening, modifying, or saving files that reside on your computer.
This brings up issues with file names and paths. When there are too many files that need to be handled, looping in combination with string formatting functionality is used.
Let’s take a look at a simple practical example of the string formatting application in file handling. Suppose we need to create directory paths using some initial information that we have inside a list:
foldersAndFiles = ["C:","Folder/Subfolder",
"picture.jpeg"]
As shown in the previous code, our list contains our computer drive name, our folder path, and the name of the file that we need to access. Suppose that the file picture.jpeg is contained inside the path generated by the folder names. We now need to generate a full correct path that can be used later to access the file. We need to get together all the list elements and join them with a slash character (/). Here is the code that would do that:
foldersAndFiles = ["C:","Folder/Subfolder",
"picture.jpeg"]
path = "/".join(foldersAndFiles) print(path)
The output you get is a string:
split()
join()
7.2 Splitting and Joining Strings 111111
Figure 7.7: Joined list elements using the join() method
This way, we have the whole path of the file named picture.jpeg. In the next chapters when we discuss file handling, you will understand that this path is used to access and process files that are identified with it.
Now, let’s look at the split() method which does the opposite of join().
The split() method will separate the string at each occurrence of a given character.
Here is an example to illustrate what we are talking about:
print("This$text$contains$unwanted$symbols"
.split("$"))
Notice that the parameter that the split() method takes is the character we want to split the text at.
This is the output:
Figure 7.8: List generated by splitting a string using the split() method
Notice that the output of the split() method is a list that contains the split strings. If your intention was to clean up the text from the unwanted characters without having a list output, we could extend our code like this:
splitting =
"This$text$contains$unwanted$symbols".
split("$")
joining = " ".join(splitting)
print (joining)
In the previous code, we are first splitting the string by removing the
“$” character from it and automatically converting the string to a list.
Then we generate spaces between the words where the “$” was residing using the join() method and automatically convert the list to a string.
Eventually you will get this output:
Figure 7.9: Text cleaned up after the split() and the join() methods have been applied to the string
Sometimes, you may want to split only a part of the string and leave the rest as it is. You can do this by using a second parameter inside the split() method:
print("This$text$contains$unwanted$symbols"
.split("$",2))
The second parameter indicates how many splits will be done starting from left to right. A parameter of two, as given in the previous code, would mean that only the first two occurrences will be split. This is what the output would look like:
Figure 7.10: Generated list from a partly split string
The split() and the join() methods can be considered simple but very important string methods.
7.2 Splitting and Joining Strings 113113
Questions for Review
1. Which of the structures best represents the following code?
"String".title()
a. object.method() b. method().object c. object.title() d. object.operator
2. What does the second line of the following code do?
a = "this is a string"
c = a.capitalize()
a. It changes the value of variable a.
b. It assigns the value of variable a to variable c.
c. It capitalizes the letter a.
d. It assigns the altered value of variable a to variable c.
3. What does the split() method return?
a. A split string.
b. Several strings.
c. A list.
d. A split tuple.
4. What does the join() method return?
a. A list.
b. A string.
c. Several joined strings.
d. A tuple.
Questions for Review
C
hapTer7 l
abe
XerCiseWithin APIs (Application Programming Interface) you usually are provided with a username or id, and a secret key. Most of these are provided together with a separator such as a colon (:). Here is an example:
82914656273523:a4edFea2786DGex
You should separate these into two separate variables, and then we will do some validation on these. The format is id:key The id should always contain only digits (numbers 0-9) and always be 14 digits long. Besides digits, the key can also contain characters and can be any length over 10 characters and less than 20 characters. If all the credentials are okay, then just print out ‘ID and Key are valid’, if they aren’t okay, display an appropriate message.
Hint: Use the isdigit() method to check if the text contained inside a string object is a digit or not.
Final Lab Solutions 115115
l
abs
oluTionpassed = '82914656273523:a4edFea2786DGex' data = passed.split(':')
id = data[0]
key = data[1]
if(id.isdigit()):
# Number is numeric.
if(len(id) == 14):
#Length of 14
if(len(key) > 10 and len(key) <
20):
print('ID and Key are valid') else:
print('Key Length isn\'t valid')
else:
print('ID wrong length') else:
print('ID isn\'t a digit')
The solution and the output would look like this in Eclipse:
Figure 7.11: Code that validates some text (upper part) and prints out the validation result (lower part)
C
hapTers
ummaryIn this chapter you were introduced to strings as objects by learning how to apply methods that altered or extracted information from them.
You were introduced to some of the methods applied to strings such as count(), capitalize() and title().
You learned how to look for a full list of methods inside the Eclipse platform, not only for string objects but for every type of object.
You worked with the join() and split() methods and you should have an idea of their importance when working with tasks such as file handling.
In the next chapter you will learn how to write your own functions that return an output.