- This topic is empty.
-
AuthorPosts
-
December 12, 2025 at 4:01 am #5860
class FileHandler(): def __init__(self, filename): self.__filename = filename def load_file(self): # ... def save_file(self, phonebook: dict): with open(self.__filename, "w") as f: for name, numbers in phonebook.items(): line = [name] + numbers f.write(";".join(line) + "\n")**Q1. Is `line` a string?**
Answer:
No.
lineis a list that contains multiple string elements.
Example:line = ["Alice", "12345", "67890"]
Q2. What does the
.join()method do?Answer:
.join()combines all items in a list into one single string, inserting a separator between each item.
Example:";".join(["A", "B", "C"])Result:
"A;B;C"
Q3. Why is the separator written first, like
";".join(list)?Answer:
Because.join()is a string method, not a list method.
The string before.join()becomes the separator (the glue) used between list items.Example:
";"= separator.join(...)= join methodlist= items to join
Q4. Can I write
list.join(";")instead?Answer:
No.
Lists do not have a.join()method.
Only strings (the separator) have the.join()method.
Q5. After joining, does the list become a string?
Answer:
No.
The list stays the same.
But.join()returns a new string containing all list elements.Example:
line = ["Alice", "12345"] result = ";".join(line)Now:
line→ still a listresult→"Alice;12345"(a string)
Q6. Does
.join()create only one string?Answer:
Yes.
The output of.join()is one single string, no matter how many items were in the list.
Q7. What is the purpose of the separator (like
";")?Answer:
Two purposes:- Human-readable formatting
Helps visually separate values. -
Machine-readable structure
Lets Python later split the string back into a list using.split(";").
Without a separator, merged data would look like this:
Alice1234567890which is impossible to separate correctly.
Q8. Can we reverse
.join()?Answer:
Yes.
Use.split(separator)to restore the list."Alice;12345;67890".split(";")Result:
["Alice", "12345", "67890"]
Q9. Why do we add
"\n"after join when writing to a file?Answer:
To move to the next line in the file.
This ensures each record is stored on its own line.
-
AuthorPosts
- You must be logged in to reply to this topic.
