Adding and removing dots
Write a function named add_dots
that takes a string and adds "."
in between each letter. For example, calling add_dots("test")
should return the string "t.e.s.t"
.
Then, below the add_dots
function, write another function named remove_dots
that removes all dots from a string. For example, calling remove_dots("t.e.s.t")
should return "test"
.
If both functions are correct, calling remove_dots(add_dots(string))
should return back the original string
for any string.
(You may assume that the input to add_dots
does not itself contain any dots.)
Â
==== SOLUTION ====
You can implement the `add_dots` and `remove_dots` functions in Python as follows:
“`python
def add_dots(s):
    return ‘.’.join(s)
def remove_dots(s):
    return s.replace(‘.’, ”)
# Test the functions
string = “test”
string_with_dots = add_dots(string)
print(string_with_dots) # Output: “t.e.s.t”
print(remove_dots(string_with_dots)) # Output: “test”
“`
Explanation:
1. `def add_dots(s):`: This function takes a string `s` as input and adds a dot between each character using the `join()` method. It returns the modified string.
2. `def remove_dots(s):`: This function takes a string `s` as input and removes all dots using the `replace()` method. It returns the modified string.
3. `string_with_dots = add_dots(string)`: This line calls the `add_dots` function to add dots between the characters of the input string `string`.
4. `remove_dots(string_with_dots)`: This line calls the `remove_dots` function to remove all dots from the string `string_with_dots`, which was obtained by adding dots to the original string. It should return the original string `”test”`.
So, the combination `remove_dots(add_dots(string))` effectively returns the original string for any input string `string`.