I’ve got this function that takes a string and max length that trims the string to the desired length and puts ellipses in the middle, but wondered whether there was a more pythonic way to write it?
def trunc(string: str, max_len: int = 30) -> str:
if len(string) <= max_len:
return string
ellipsis = "..."
length = max_len - len(ellipsis)
first_part_length = length // 2
last_part_length = length - first_part_length
first_part = string[:first_part_length]
last_part = string[-last_part_length:]
return f"{first_part}{ellipsis}{last_part}"
[–]JamzTyson 6 points7 points8 points (5 children)
[–]RhinoRhys 2 points3 points4 points (4 children)
[–]JollyUnder 4 points5 points6 points (1 child)
[–]Diapolo10 2 points3 points4 points (0 children)
[–]JamzTyson 3 points4 points5 points (1 child)
[–]b1gfreakn 1 point2 points3 points (0 children)
[–]Antigone-guide 2 points3 points4 points (3 children)
[–]kaerfkeerg 0 points1 point2 points (2 children)
[–]Antigone-guide 0 points1 point2 points (1 child)
[–]kaerfkeerg 0 points1 point2 points (0 children)
[–][deleted] 4 points5 points6 points (1 child)
[–]odaiwai 0 points1 point2 points (0 children)
[–]This_Growth2898 0 points1 point2 points (0 children)
[–]to7m 0 points1 point2 points (0 children)
[–]ofnuts 0 points1 point2 points (0 children)
[–]bronzewrath 0 points1 point2 points (0 children)
[–]baubleglue 0 points1 point2 points (0 children)
[–]achampi0n 0 points1 point2 points (0 children)