tmp, out = "",""
for ch in s:
if ch.isspace() or ch in {",", "."}:
out += "{}{}{}{}".format(tmp[0], len(tmp) - 2, tmp[-1], ch) if len(tmp) > 3 else tmp + ch
tmp = ""
else:
tmp += ch
out += "{}{}{}".format(tmp[0], len(tmp) - 2, tmp[-1]) if len(tmp) > 3 else tmp
print(out)
a11y,r4m g2d bye
If you only want alpha characters use str.isalpha:
tmp, out = "", ""
for ch in s:
if not ch.isalpha():
out += "{}{}{}{}".format(tmp[0], len(tmp) - 2, tmp[-1], ch) if len(tmp) > 3 else tmp + ch
tmp = ""
else:
tmp += ch
out += "{}{}{}".format(tmp[0], len(tmp) - 2, tmp[-1]) if len(tmp) > 3 else tmp
print(out)
a11y,r4m g2d bye
The logic is the same for both, it is just what we check for that differs, if not ch.isalpha() is False we found a non alpha character so we need to process the tmp string and add it to out output string. if len(tmp) is not greater than 3 as per the requirement we just add the tmp string plus the current char to our out string.
We need a final out += "{}{}{} outside the loop to catch when a string does not end in a comma, space etc.. If the string did end in a non-alpha we would be adding an empty string so it would make no difference to the output.
It will preserve punctuation and spaces:
s = "accessibility,random good bye !! foobar?"
def func(s):
tmp, out = "", ""
for ch in s:
if not ch.isalpha():
out += "{}{}{}{}".format(tmp[0], len(tmp) - 2, tmp[-1], ch) if len(tmp) > 3 else tmp + ch
tmp = ""
else:
tmp += ch
return "{}{}{}".format(tmp[0], len(tmp) - 2, tmp[-1]) if len(tmp) > 3 else tmp
print(func(s,3))
a11y,r4m g2d bye !! f4r?
reis a bit of an overkill for this, in my opinion. I'd just usemystring[0]+str(len(mystring)-2)+mystring[-1]and anifstatement to see when to apply thismystringhas separate individual words (likeaccessibility,random good bye) and not itself is a word.mystringis just one word. If you have comma separated words you can just domycomaseparatedstring.split(',')to get a list of the contents ofmycomaseparatedstringseparated by commas. Then proceed as withmystring. Sorry, thought this was clear - it was to me because I know Python, perhaps I should have been clearer.