Skip to content

Commit

Permalink
Add code for string join tutorial
Browse files Browse the repository at this point in the history
  • Loading branch information
martin-martin committed Jan 22, 2025
1 parent 2b76a5c commit 6afb7d2
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
11 changes: 11 additions & 0 deletions python-join-strings/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# How to Join a String in Python

This folder contains code associated with the Real Python tutorial on [How to Join a String in Python](https://realpython.com/python-join-string/).

## About the Author

Martin Breuss - Email: martin@realpython.com

## License

Distributed under the MIT license. See `LICENSE` for more information.
5 changes: 5 additions & 0 deletions python-join-strings/event_log.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"2025-01-24 10:00": ["click", "add_to_cart", "purchase"],
"2025-01-24 10:05": ["click", "page_view"],
"2025-01-24 10:10": ["page_view", "click", "add_to_cart"]
}
26 changes: 26 additions & 0 deletions python-join-strings/format_event_log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import json


def load_log_file(file_path):
with open(file_path, mode="r", encoding="utf-8") as event_log_file:
return json.load(event_log_file)


def format_event_log(event_log):
lines = []
for timestamp, events in event_log.items():
# Convert the events list to a string separated by commas.
event_list_str = ", ".join(events)
# Create a single line string.
line = f"{timestamp} => {event_list_str}"
lines.append(line)

# Join all lines with a newline separator.
return "\n".join(lines)


if __name__ == "__main__":
log_file_path = "event_log.json"
event_log = load_log_file(log_file_path)
output = format_event_log(event_log)
print(output)

0 comments on commit 6afb7d2

Please sign in to comment.