Home > Back-end >  How to append to a string?
How to append to a string?

Time:10-23

Here I am counting each character in a string and return that character with it's number of occurences in the string. e.g.: ab("aabbc") and return a string: a2b2c1

However I have a list here where instead of returning a2b2c1, it returns ['a',2,'b',2,'c',1]. I want it to return it in the form of a string, and not a list.

Here's what I did:

def ab(n):

    char = []
    
    for i in n:
        if i not in char:
            char.append(i)
            count = n.count(i)
            char.append(count)
    return(char)  

CodePudding user response:

Consider recognizing that strings are immutable in python:

def ab(n):
    char = []
    i = 0
    while i < len(n):
        run_length = 1
        while i   1 < len(n) and n[i] == n[i   1]:
            run_length  = 1
            i  = 1
        char.append(str(run_length))
        char.append(n[i])
        i  = 1
    return ''.join(char)

print(f'{ab("aabbc") = }')
print(f'{ab("aabcaa") = }')

Output:

ab("aabbc") = '2a2b1c'
ab("aabcaa") = '2a1b1c2a'

Alternatively, if you do not actually need to implement run-length encoding, you could utilize collections.Counter:

>>> from collections import Counter
>>> n = 'aabcaa'
>>> ''.join(f'{c}{k}' for k, c in Counter(n).items())
'4a1b1c'

CodePudding user response:

Considering strings are immutable in Python, you may wish to use re.sub with a lambda to generate a new string with the run length encoding.

import re

s = "aaaabbc"

re.sub(r"(\D)(\1*)", lambda m: f"{m.group(1)}{1 len(m.group(2))}", s)
# 'a4b2c1'

CodePudding user response:

There is dictionary in python for this kind of problem Here how it works:

words = "aabbc"

occurrences = {}

for char in words:
    char[i] =  char.get(i, 0)   1

print(occurrences)

Output:

{'a': 2, 'b': 2, 'c': 1}

To get dictionary value:

print(occurrences["a"])

Output:

2

CodePudding user response:

Just to point out there is run_length in more_itertools just for this purpose:

from more_itertools import run_length

s = 'abbcccdee'

#print(list(run_length.encode(s)))
#[('a', 1), ('b', 2), ('c', 3), ('d', 1), ('e', 2)]
ans = ''
for t in run_length.encode(s):
    ans  = str(t[1]) t[0]

    
print(ans)
'1a2b3c1d2e'
  • Related