Skip to content

Commit

Permalink
Add truncate_mid and flatten string tools
Browse files Browse the repository at this point in the history
  • Loading branch information
ejohb committed Nov 22, 2024
1 parent bb58ab1 commit c5c97cd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
27 changes: 25 additions & 2 deletions fmtr/tools/string_tools.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from collections import namedtuple

import re
from collections import namedtuple
from string import Formatter
from typing import List

ELLIPSIS = '…'
formatter = Formatter()

Segment = namedtuple('Segment', ['literal_text', 'field_name', 'format_spec', 'conversion'])
Expand Down Expand Up @@ -80,6 +80,29 @@ def sanitize(*strings, sep: str = '-') -> str:
return string


def truncate_mid(text, length=None, sep=ELLIPSIS):
"""
Truncate a string to `length` characters in the middle
"""
if len(text) <= length or not length:
return text
half_length = (length - 3) // 2
return text[:half_length] + sep + text[-half_length:]


def flatten(raw):
"""
Flatten a multiline string to a single line
"""
lines = raw.splitlines()
text = ' '.join(lines)
return text


class Mask:
"""
Expand Down
2 changes: 1 addition & 1 deletion fmtr/tools/version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.0.2
1.0.3

0 comments on commit c5c97cd

Please sign in to comment.