简体   繁体   中英

Count occurrences of char in a single string

string = input(" ")
count = string.count()
print(string + str(count))

Need to use a for loop to get the output: ll2a1m1a1

Use groupby from itertools

>>> from itertools import groupby
>>> s = 'llama'
>>> [[k, len(list(g))] for k, g in groupby(s)]
[['l', 2], ['a', 1], ['m', 1], ['a', 1]]

If you want exactly that output you asked, try the following, and as suggested by @DanielMesejo, use sum(1 for _ in g) instead of len(list(g)) :

>>> from itertools import groupby
>>> s = 'llama'
>> groups = [[k, sum(1 for _ in g)] for k, g in groupby(s)]
>>> ''.join(f'{a * b}{b}' for a, b in groups)
'll2a1m1a1'

This works for any word you want, let's say the word is 'happen', so

>>> from itertools import groupby
>>> s = 'happen'
>> groups = [[k, sum(1 for _ in g)] for k, g in groupby(s)]
>>> ''.join(f'{a * b}{b}' for a, b in groups)
'h1a1pp2e1n1'

Look bud, you gotta explain more, this loops through and counts how many times each letter and prints it out.

greeting = 'llama'
for i in range(0, len(greeting)):
    #start count at 1 for original instance.
    count = 1
    for k in range(0, len(greeting)):
        # check letters are not the same position letter.
        if not k == i:
            #check if letters match
            if greeting[i] == greeting[k]:
                count += 1
    print(greeting[i] + str(count))

a more basic approach:

string = 'llama'

def get_count_str(s): 
    previous = s[0]
    for c in s[1:]:
        if c != previous:
            yield f'{previous}{len(previous)}'
            previous = c
        else:
            previous += c


    # yield last
    yield f'{previous}{len(previous)}'

print(*get_count_str(string ), sep='')

output:

ll2a1m1a1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM