Registry / data / srt
library3.5.3pypypi✓ verified 22d ago

SRT is a tiny, yet featureful Python library designed for robust parsing, modification, and composition of SRT subtitle files. It can handle many broken SRT files and has no dependencies beyond the Python Standard Library. The current version is 3.5.3, with an active, though not rapid, release cadence.

pip install srt
INSTALL
IMPORT
SIG · SRT
S
srt
datapythonv3.5.3
Install
2.7s avg
Import
50ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.5.3 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.052s · 19.2MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.7s · import 0.048s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

srt
import srt
parse
srt.parse(...)
from srt import srt_parse
The parse function is directly accessible via `srt.parse` after importing the module, not as a separate named import.
compose
srt.compose(...)
Subtitle
from srt import Subtitle
srt.Subtitle()
While `srt.Subtitle` is available, it's more idiomatic to import `Subtitle` directly for object creation.

This quickstart demonstrates how to parse an SRT string into a list of `Subtitle` objects, access and modify their properties, and then compose them back into an SRT formatted string. It also shows how to create a new `Subtitle` object and use `srt.sort_and_reindex`.

import srt srt_content = '''\ 1 00:01:00,000 --> 00:01:03,000 Hello, world! 2 00:01:04,000 --> 00:01:07,000 This is a test subtitle. ''' # Parse an SRT string into Subtitle objects subtitle_generator = srt.parse(srt_content) subtitles = list(subtitle_generator) print(f"Parsed {len(subtitles)} subtitles.") for sub in subtitles: print(f"Index: {sub.index}, Start: {sub.start}, End: {sub.end}, Content: {sub.content}") # Modify a subtitle if subtitles: subtitles[0].content = "Modified content!" subtitles[0].start.seconds = 5 # Compose Subtitle objects back into an SRT string composed_srt = srt.compose(subtitles) print("\n--- Composed SRT ---") print(composed_srt) # Example of creating a new subtitle new_sub = srt.Subtitle(index=3, start=srt.timedelta(seconds=10), end=srt.timedelta(seconds=12), content='A brand new subtitle.') subtitles.append(new_sub) composed_with_new = srt.compose(srt.sort_and_reindex(subtitles)) print("\n--- Composed with new and reindexed ---") print(composed_with_new)
Debug
Known issues
gotchaWhen reading SRT content from a file, ensure correct file encoding (e.g., UTF-8, latin-1). While the library is Unicode compliant, `srt.parse()` expects a Python string, so incorrect file reading can lead to `UnicodeDecodeError` or garbled text if not handled at the file reading stage.
fix
Specify the `encoding` when opening the file, e.g., `with open('file.srt', 'r', encoding='utf-8') as f: srt_data = f.read()`.
affects: All versions
breakingThe `srt.parse()` function will raise an `srt.SRTParseError` if it encounters malformed SRT data and `ignore_errors` is `False` (which is the default behavior).
fix
Handle `SRTParseError` with a `try...except` block, or set `ignore_errors=True` in `srt.parse()` to skip invalid blocks and continue parsing, though this might result in incomplete subtitle data. For example: `subs = list(srt.parse(srt_content, ignore_errors=True))`.
affects: All versions
gotchaBy default, `srt.compose()` operates in `strict=True` mode, which disallows blank lines within a subtitle's content. Including blank lines in strict mode violates the SRT standard and can lead to issues with media players.
fix
Avoid blank lines in subtitle content when composing SRTs. If you absolutely need to compose an SRT with blank lines (not recommended), you can set `strict=False`: `srt.compose(subtitles, strict=False)`.
affects: All versions
gotchaThe `srt.sort_and_reindex()` function has an `in_place` parameter. If `in_place=True`, it modifies the input list of subtitles directly rather than returning a new sorted list. This can lead to unexpected side effects if you expect the original list to remain unchanged.
fix
If you want a new, sorted, and reindexed list without modifying the original, ensure you pass a copy or explicitly handle the return value. For example, `new_sorted_subs = srt.sort_and_reindex(list(original_subs))` if `in_place` is True, or simply `new_sorted_subs = srt.sort_and_reindex(original_subs, in_place=False)` if the function supports `in_place=False` (which it does not directly, but the default behavior is to create a new list if `in_place` is not specified as True. Always check the function signature). Note: for `srt.sort_and_reindex`, the default behavior implicitly returns a new list if `in_place` is not explicitly set to `True` for older versions, for newer versions the parameter is `skip` and `in_place` is not present, so clarification on its usage is key in current documentation. Current `srt.sort_and_reindex` function takes `subtitles`, `start_index`, and `skip`. The function returns a new list without modifying the original, so `in_place` is not a concern for the current API. Rephrasing this warning for current version: The *returned* list from `srt.sort_and_reindex` should be used as it will contain the sorted and re-indexed subtitles. If you're appending this back to an existing list, be careful to replace or extend, not just append.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'srt'
The 'srt' library has not been installed in the current Python environment or is not accessible.
fix
pip install srt
AttributeError: module 'srt' has no attribute 'read'
The 'srt' library functions ('parse', 'compose') operate on strings, not file objects directly, and do not provide built-in file I/O methods.
fix
import srt

# To parse from a file
with open('subtitles.srt', 'r', encoding='utf-8') as f:
    srt_string = f.read()
subtitles = srt.parse(srt_string)

# To compose to a file
composed_srt = srt.compose(subtitles)
with open('output.srt', 'w', encoding='utf-8') as f:
    f.write(composed_srt)
TypeError: expected string or bytes-like object, not list
The `srt.parse()` function expects a single string containing the entire SRT subtitle content, not a list of individual lines.
fix
import srt

# If you have lines from a file readlines()
lines = [
    "1\n",
    "00:00:01,000 --> 00:00:02,000\n",
    "Hello\n",
    "\n",
    "2\n",
    "00:00:02,500 --> 00:00:03,500\n",
    "World\n",
    "\n"
]
srt_string = "".join(lines) # Assumes lines already contain newlines
subtitles = srt.parse(srt_string)
TypeError: 'Subtitle' object is not subscriptable
`srt.parse()` yields `Subtitle` objects, which are custom objects and not subscriptable like lists or dictionaries. Their properties (e.g., content, start, end) are accessed via attributes.
fix
import srt

srt_data = """1
00:00:01,000 --> 00:00:02,000
Hello
"""
subtitles = srt.parse(srt_data)
for sub in subtitles:
    print(f"Index: {sub.index}")
    print(f"Content: {sub.content}")
    print(f"Start: {sub.start}")
AttributeError: 'Subtitle' object has no attribute 'text'
Users often incorrectly try to access the subtitle text using a non-existent attribute like `text` instead of the correct `content` attribute.
fix
import srt

srt_data = """1
00:00:01,000 --> 00:00:02,000
Hello
"""
subtitles = list(srt.parse(srt_data))
if subtitles:
    print(subtitles[0].content) # Correct way to access
Upgrade
Version history
3.5.3latest on PyPI · released Mar 28, 2023
Audit
Dependencies

No dependency data recorded yet.

Agent activity
21 hits · last 30 days
node
18
OpenAI (training)
1
Resources
srt — pip install srt · libregistry