how to insert "|" in "-" every 5 like this?

Viewed 52

I want to do like this picture, but I have no idea to insert "|" enter image description here

and this is my code.

"""test"""
def counts():
    """process"""
    text = input()
    text_abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for i in text_abc:
        count_text = text.count(i)
        if count_text > 0:
            ans = "-"* count_text
            print("%s : %s"%(i, ans))
counts()

it output like this

my input:"aaaaaaaabbbbbcccdd"
my output:
a : --------
b : -----
c : ---
d : --

how can i do? Thanks in advance for any help that you are able to provide. ps. sorry for my english,I'm not good in english

3 Answers

The simplest way would just be to put it into ans via str.replace(), which will by default replace an arbitrary number of occurrences starting at the front:

ans = ("-" * count_text).replace('-----', '-----|')
>>> counts()
aaaaaaaabbbbbcccdd
a : -----|---
b : -----|
c : ---
d : --

you can also do it like this:

ans = "-" * count_text
ans = '|'.join(ans[i:i+5] for i in range(0, len(ans), 5))

full code:

def counts():
    """process"""
    text = input()
    text_abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    for i in text_abc:
        count_text = text.count(i)
        if count_text > 0:
            ans = "-" * count_text
            ans = '|'.join(ans[i:i+5] for i in range(0, len(ans), 5))
            print("%s : %s"%(i, ans))

counts()

output:

ex.1

"aaaaaaaabbbbbcccdd"
a : -----|---
b : -----
c : ---
d : --

ex.2

"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbbbcccccccccccccccccccccddyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
a : -----|-----|-----|-----|-----|-----|-----|-
b : ----
c : -----|-----|-----|-----|-
d : --
y : -----|-----|-----|-----|-----|-----|----

I've used Counter module from collections package, also formatting is in 3.6, I'm not sure if collections works well for versions less than 3.6 please cross check.

from collections import Counter

"""test"""
def counts():
    """process"""
    text = Counter(input()) # counter returns a list with key as the element and value as it's frequency

    for i in text.keys(): # iterating in keys
        count_text = text[i]  # getting the frequency of that alphabet
        pattern = ['|-' if (_ % 5 == 0 and _ != 0) else '-' for _ in range(count_text)] # creating a list in which we put '|-' if the position if mod of 5 else we just put '-'.
        patternString = ''.join(pattern) # then we convert it to string
        print(f'{i}: {patternString} ')

counts()
Related