Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add spaces before every repeating string in list

I am struggling a bit with the following issue. I want to add empty spaces in front of repeating entries.

What it looks like:               What it should look like:
a                                 a
asdf                              asdf
asdf                                asdf
asdf                                asdf
b                                 b
cc                                cc
cc                                  cc
e                                 e

I tried a few things but they all tend to either add to many spaces in the follow up entries or just plain don’t work.

test = ["a", "asdf", "asdf", "asdf", "b", "c", "c"]
for i in range(0, len(test)):
    temp = test[i]
    # I use a try here to avoid out of bounds exceptions
    try: 
        if test[i] == test[i + 1]:        
            # checking for how many repeating entries exist after the first one 
            for j in range(1, len(test)):
                if temp == test[i + j]:
                    test[i + j] = "   " + temp
                else:
                    break
                
    except:
        pass

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The main issue here is that you are updating your array entries to have spaces in them, and then checking if they are equal to the other entries that do not have the spaces. To overcome this, you should check if they are equal with white-space removed.

You can also do this more effectively by having a spaces variable and updating it after each entry depending on whether the entry is the same as the one before or not. The following code should do what you are looking for.

test = ["a", "asdf", "asdf", "asdf", "b", "c", "c"]
spaces = 0
print(test[0]) # prints are just to show the output
for i in range(1, len(test)):
    if (test[i].lstrip() == test[i-1].lstrip()):
        spaces = 1
    else:
        spaces = 0
    test[i] = " "*spaces + test[i]
    print(test[i]) # prints are just to show the output

Output:

a
asdf
 asdf
 asdf
b
c
 c
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading