def char_ranges(s):
    if len(s) == 0:
        return s

    result = []
    start = s[0]
    end = s[0]

    for i in range(1, len(s)):
        if ord(s[i]) - ord(s[i-1]) == 1:
            end = s[i]
        else:
            if start == end:
                result.append(start)
            else:
                result.append(f"{start}-{end}")

            start = s[i]
            end = s[i]

    if start == end:
        result.append(start)
    else:
        result.append(f"{start}-{end}")

    return "".join(result)

print(char_ranges("abcdxyz")) # "a-dx-z"
print(char_ranges("abcdmps")) # "a-dpms"
print(char_ranges("01234mno")) # "0-4m-o"
print(char_ranges("enjks")) # "enjks"
print(char_ranges("abdefgxy"))

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: