The join Function

In Snap!, when we wanted to turn a list into a text, we used the combine HOF along with the join reporter. In Python, things are a little weirder, but not so bad. Suppose we want to combine ['h', 'e', 'l', 'l', 'o'] into a string. To do this, we'd do the following:


>>> "".join(["h", "e", "l", "l", "o"])
'hello'
                    

In this case, we're using the join function that is built into every string. In this case we're asking the empty string "" to use its join command. We can also ask other strings to join lists, for example, we could request that the string " and " to perform the join operation. This would result in the characters being joined, but with an " and " between each in the joined string.


>>> " and ".join(["h", "e", "l", "l", "o"])
'h and e and l and l and o'

This trick of using "".join to convert lists to strings will be useful for using list comprehensions on strings.

List Comprehensions and Strings

We can use list comprehensions to perform string operations as well. For example, suppose we want to write a function that gets rid of any letters that are alphabetically less than m. We might try something like:


def less_than_m(text):
    return [letter for letter in text if letter < "m"]

This almost works! However, there's a problem: List comprehensions always return a list, not a string. Even though the list comprehension knows how to iterate through the string, it returns a list of characters, not a string.


>>> less_than_m("buddy")
['b', 'd', 'd']

To deal with this, we'll simply use the trick we saw in the section above:


>>> "".join(less_than_m("buddy"))
'bdd'

Exercise 4: Substitute Base

Write a function substitute_base that takes as input a string representing a DNA sequence, a base to be substituted (old), and a base that is to take the place of the base being substituted (new). Old and New could be any letter, so make sure to keep your code general! This function should return a string with the proper base substituted. Use a list comprehension along with the "".join trick.


>>> substitute_base("AAGTTAGTCA", "A", "C")
"CCGTTCGTCC"
        

Hint: Create a helper function that considers what to do with only one character and map this function over each character using your comprenehsion (similar to what you may have done for the Project 1 word guessing game).

Just so you know, there is a built in string function called replace that you'd use in real world programming instead of doing it the way we require in this problem. We don't want you to use it for this function though!