Skip to content

Commit 7c0a16d

Browse files
authored
Merge pull request #630 from realpython/python-join-strings
Add code for string join tutorial
2 parents 4de2690 + 96b7399 commit 7c0a16d

File tree

6 files changed

+60
-0
lines changed

6 files changed

+60
-0
lines changed

python-join-strings/README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# How to Join Strings in Python
2+
3+
This folder contains code associated with the Real Python tutorial [How to Join Strings in Python](https://realpython.com/python-join-string/).
4+
5+
## About the Author
6+
7+
Martin Breuss - Email: [email protected]
8+
9+
## License
10+
11+
Distributed under the MIT license. See `LICENSE` for more information.

python-join-strings/event_log.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"2025-01-24 10:00": ["click", "add_to_cart", "purchase"],
3+
"2025-01-24 10:05": ["click", "page_view"],
4+
"2025-01-24 10:10": ["page_view", "click", "add_to_cart"]
5+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import json
2+
3+
4+
def load_log_file(file_path):
5+
with open(file_path, mode="r", encoding="utf-8") as file:
6+
return json.load(file)
7+
8+
9+
def format_event_log(event_log):
10+
lines = []
11+
for timestamp, events in event_log.items():
12+
# Convert the events list to a string separated by commas
13+
event_list_str = ", ".join(events)
14+
# Create a single line string
15+
line = f"{timestamp} => {event_list_str}"
16+
lines.append(line)
17+
18+
# Join all lines with a newline separator
19+
return "\n".join(lines)
20+
21+
22+
if __name__ == "__main__":
23+
log_file_path = "event_log.json"
24+
event_log = load_log_file(log_file_path)
25+
output = format_event_log(event_log)
26+
print(output)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
cities = ["Hanoi", "Adelaide", "Odessa", "Vienna"]
2+
travel_path = "->".join(cities)
3+
print(travel_path)
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
cities = ["Hanoi", "Adelaide", "Odessa", "Vienna"]
2+
separator = "->"
3+
4+
travel_path = ""
5+
for i, city in enumerate(cities):
6+
travel_path += city
7+
if i < len(cities) - 1:
8+
travel_path += separator
9+
10+
print(travel_path)

python-join-strings/url_builder.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
base_url = "https://example.com/"
2+
subpaths = ["blog", "2025", "01", "my-post"]
3+
4+
full_url = base_url + "/".join(subpaths)
5+
print(full_url)

0 commit comments

Comments
 (0)