Skip to content

Commit 17e7a8b

Browse files
committed
Add code examples for string split tutorial
1 parent 774ff3c commit 17e7a8b

File tree

5 files changed

+35
-0
lines changed

5 files changed

+35
-0
lines changed

split-strings/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# How to Split a String in Python
2+
3+
This folder provides the code examples for the Real Python tutorial [How to Split a String in Python](https://realpython.com/python-string-split-concatenate-join/).
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
log_data = """2025-01-15 08:45:23 INFO User logged in
2+
2025-01-15 09:15:42 ERROR Failed to connect to server
3+
2025-01-15 10:01:05 WARNING Disk space running low"""
4+
5+
log_lines = log_data.splitlines()
6+
7+
for line in log_lines:
8+
if "ERROR" in line:
9+
print(line)

split-strings/extract_log_info.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
log_line = "2025-01-15 08:45:23 INFO User logged in from IP 10.0.1.1"
2+
3+
date, time, log_level, message = log_line.split(maxsplit=3)
4+
5+
print(f"Date: {date}")
6+
print(f"Time: {time}")
7+
print(f"Log Level: {log_level}")
8+
print(f"Message: {message}")

split-strings/names_with_titles.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
person = "Dr. Jane Doe, PhD Professor of Biology"
2+
3+
title, first_name, last_name, rest_info = person.split(maxsplit=3)
4+
5+
print(f"Title: {title}")
6+
print(f"First Name: {first_name}")
7+
print(f"Last Name: {last_name}")
8+
print(f"Additional Info: {rest_info}")

split-strings/split_logs_regex.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import re
2+
3+
log_line = "2025-01-15 08:45:23 INFO User logged in from IP 10.0.1.1"
4+
pattern = r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s(\w+)\s"
5+
components = re.split(pattern, log_line)
6+
7+
print(components)

0 commit comments

Comments
 (0)