SRT (Subtitle Parsing)

3.5.3 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

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)

view raw JSON →