To parse a string in Python, break it into pieces with split(), clean each piece with strip(), then convert the pieces you need with int() or float(). For patterns, use the re module:
qty, price = "3, 24.99".split(",")
total = int(qty) * float(price) # 74.97
Every script below ran in Command Prompt on Python 3.12.5. Save each one as a .py file and run it with python file.py to follow along.
In this tutorial, we’ll parse an order line, key=value settings, a log entry with regex, JSON and date strings, and messy numbers that would crash int().
Parse a delimited string with split() and strip()
For a comma-separated order line, split it, strip the spaces, and unpack the parts:
line = "1042, Emily Carter, Austin TX, 3, 24.99"
order_id, name, city, qty, price = [part.strip() for part in line.split(",")]
qty, price = int(qty), float(price)
print(order_id, name, city, sep=" | ")
print(f"{qty} x ${price:.2f} = ${qty * price:.2f}")
print("Austin TX 78701".split(maxsplit=1)) # stop after the first split
Output:
1042 | Emily Carter | Austin TX
3 x $24.99 = $74.97
['Austin', 'TX 78701']

maxsplit=1 splits once, so the state and ZIP code stay together. There’s more on separators in splitting a string by comma in Python.
Parse key=value text with partition()
partition() splits at the first separator only and always returns three parts, so it won’t raise an error when the separator is missing:
settings = ["region = us-east", "timeout=30", "debug"]
for s in settings:
key, sep, value = s.partition("=")
print(repr(key.strip()), repr(value.strip()), "found" if sep else "no '='")
path = "reports/2026/october/sales.csv"
folder, _, filename = path.rpartition("/")
print(folder, "->", filename)
Output:
'region' 'us-east' found
'timeout' '30' found
'debug' '' no '='
reports/2026/october -> sales.csv

rpartition() splits at the last separator, handy for paths. To grab text between two markers instead, see extracting a substring between two characters.
How do you parse a string with regular expressions?
When fields don’t share one delimiter, use a regex. Named groups give you a dictionary, and findall() collects every key=value pair:
import re
log = "2026-10-23 08:15:42 INFO order=1042 user=ecarter total=$74.97"
m = re.search(r"(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>[\d:]+) (?P<level>\w+)", log)
print(m.groupdict())
fields = dict(re.findall(r"(\w+)=(\S+)", log))
print(fields)
print("Total as a number:", float(fields["total"].lstrip("$")))
Output:
{'date': '2026-10-23', 'time': '08:15:42', 'level': 'INFO'}
{'order': '1042', 'user': 'ecarter', 'total': '$74.97'}
Total as a number: 74.97

Strip the dollar sign before float(). For more patterns, read regular expressions in Python, or extracting numbers from a string if digits are all you need.
Parse JSON, list and date strings with the standard library
Don’t split structured text by hand; the standard library has a parser for each format:
import ast
import json
from datetime import datetime
payload = '{"customer": "James Miller", "state": "OH", "paid": true, "amount": 129.50}'
data = json.loads(payload)
print(data["customer"], data["paid"], data["amount"])
items = ast.literal_eval("['laptop', 'mouse', 'monitor']")
print(items, type(items).__name__)
shipped = datetime.strptime("10/23/2026 2:30 PM", "%m/%d/%Y %I:%M %p")
print(shipped, shipped.strftime("%A"))
Output:
James Miller True 129.5
['laptop', 'mouse', 'monitor'] list
2026-10-23 14:30:00 Friday

I use ast.literal_eval(), never eval(), on untrusted text. There are more JSON examples in converting a JSON string to a dictionary and format codes in converting a string to datetime in Python.
Parse numbers from a string without crashing
User input breaks int() fast. Wrap it in try/except ValueError to return a default instead of crashing:
def to_int(text, default=None):
try:
return int(text)
except ValueError:
return default
for raw in [" 42 ", "3.5", "N/A", "-7", "1,200"]:
print(f"{raw!r:>8} -> {to_int(raw)}")
Output:
' 42 ' -> 42
'3.5' -> None
'N/A' -> None
'-7' -> -7
'1,200' -> None
int() already ignores surrounding spaces, but not decimals or thousands separators. Remove commas first, as shown in removing commas from a string in Python.
Which Python string parsing method should you use?
| Input | Method | Returns |
|---|---|---|
a, b, c | split() + strip() | list of strings |
key=value | partition() | 3-part tuple |
| Mixed text, logs | re.search(), re.findall() | match, list |
| JSON | json.loads() | dict or list |
| Dates | datetime.strptime() | datetime |
A few more string guides pair well with this one:
- Split a string with regex in Python
- Split strings with multiple delimiters
- Convert a string to a list in Python
- Convert a string to an integer in Python
Frequently asked questions
What does parsing a string mean in Python?
It means pulling structured values, like fields, numbers or dates, out of text.
How do I split a string and convert the parts to numbers?
Use [int(x) for x in s.split(",")], or float() for decimals.
What is the difference between split() and partition()?
split() returns a list of every piece; partition() splits once and always returns three parts.
How do I parse a string that looks like a list?
Use ast.literal_eval("['a', 'b']"), or json.loads() if it’s valid JSON.
How do I parse a date string in Python?
Call datetime.strptime(text, format), for example "%m/%d/%Y" for 10/23/2026.
Where are Python’s string methods documented?
See str.split() in the Python docs.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn