SRT (Subtitle Parsing)
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.
Warnings
- gotcha When 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.
- breaking The `srt.parse()` function will raise an `srt.SRTParseError` if it encounters malformed SRT data and `ignore_errors` is `False` (which is the default behavior).
- gotcha By 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.
- gotcha The `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.
Install
-
pip install srt
Imports
- srt
import srt
- parse
srt.parse(...)
- compose
srt.compose(...)
- Subtitle
from srt import Subtitle
Quickstart
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)