你可以试试这个:
string = 'assdggg' compression = '' for char in string : if char not in compression : if string.count(char) != 1 : compression += str(string.count(char)) compression += char print(compression) #'a2sd3g'