How to Parse a String in Python

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']
Command Prompt output of Python parsing an order string with split and strip, then converting quantity and price to numbers
The order line becomes five clean fields, and the quantity and price turn into numbers for the total.

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
Command Prompt output of Python partition parsing key=value settings and rpartition splitting a file path
Each setting splits into a key and a value; the line without an equals sign comes back with an empty value.

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
Command Prompt output of Python re.search named groups and re.findall parsing a log line into dictionaries
The date, time and level come out as named groups, and the key=value pairs turn into a dictionary.

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
Command Prompt output of Python json.loads, ast.literal_eval and datetime.strptime parsing JSON, a list string and a US date
JSON turns into a dictionary with a real boolean, the list string becomes a list, and the US date becomes a datetime.

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?

InputMethodReturns
a, b, csplit() + strip()list of strings
key=valuepartition()3-part tuple
Mixed text, logsre.search(), re.findall()match, list
JSONjson.loads()dict or list
Datesdatetime.strptime()datetime

A few more string guides pair well with this one:

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.