diff --git a/python-join-strings/README.md b/python-join-strings/README.md new file mode 100644 index 0000000000..bf18907157 --- /dev/null +++ b/python-join-strings/README.md @@ -0,0 +1,11 @@ +# How to Join Strings in Python + +This folder contains code associated with the Real Python tutorial [How to Join Strings 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. diff --git a/python-join-strings/event_log.json b/python-join-strings/event_log.json new file mode 100644 index 0000000000..2b46d4d9fe --- /dev/null +++ b/python-join-strings/event_log.json @@ -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"] +} \ No newline at end of file diff --git a/python-join-strings/format_event_log.py b/python-join-strings/format_event_log.py new file mode 100644 index 0000000000..9c13ecc215 --- /dev/null +++ b/python-join-strings/format_event_log.py @@ -0,0 +1,26 @@ +import json + + +def load_log_file(file_path): + with open(file_path, mode="r", encoding="utf-8") as file: + return json.load(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) diff --git a/python-join-strings/join_concatenation.py b/python-join-strings/join_concatenation.py new file mode 100644 index 0000000000..8d50f7a856 --- /dev/null +++ b/python-join-strings/join_concatenation.py @@ -0,0 +1,3 @@ +cities = ["Hanoi", "Adelaide", "Odessa", "Vienna"] +travel_path = "->".join(cities) +print(travel_path) diff --git a/python-join-strings/plus_loop_concatenation.py b/python-join-strings/plus_loop_concatenation.py new file mode 100644 index 0000000000..88e4865bf4 --- /dev/null +++ b/python-join-strings/plus_loop_concatenation.py @@ -0,0 +1,10 @@ +cities = ["Hanoi", "Adelaide", "Odessa", "Vienna"] +separator = "->" + +travel_path = "" +for i, city in enumerate(cities): + travel_path += city + if i < len(cities) - 1: + travel_path += separator + +print(travel_path) diff --git a/python-join-strings/url_builder.py b/python-join-strings/url_builder.py new file mode 100644 index 0000000000..2787429596 --- /dev/null +++ b/python-join-strings/url_builder.py @@ -0,0 +1,5 @@ +base_url = "https://example.com/" +subpaths = ["blog", "2025", "01", "my-post"] + +full_url = base_url + "/".join(subpaths) +print(full_url)