简体   繁体   中英

remove characters from a list and add a line break from each element

I'm working on a project in which I must create some objects for this use a dictionary in which the objects are saved with their identifier, now, I need that only appears the attribute of the objects, without needing the identifier, for this convert the values of the dictionary in a list, but I can not remove things like [ ] or give line breaks

my code is:

class myclass():
   
    def __init__(self, x):
        self.x = x 




    list_obj = [] 
    list_attrs = []
    list_values = []
    for i in range (3):
        obj = myclass(' U')
        y= list_obj.append(obj)
        b=list(y.b())
        list_values.append(b)
        

print(list_values)

my output is:

['U'], ['U'], ['U']]

Any idea how to do this?.I tried to use strip but it doesn't give me the desired result or I even thought of converting the whole list into a string and maybe I could do it, but I can't get it.

The problem is that you are not printing a string, you are printing a list. Python print has a built in feature to print list like that. To format list in other ways you can check out this https://www.geeksforgeeks.org/print-lists-in-python-4-different-ways/

One way to do what you want:

for v in list_values:
    print(*v, sep='\n')

First flatten the list, then combine each element of the list with a line break as an seperator. You get a string, and if you print it it looks like you expect it.

lst = [['Ultra1', 'Max1', 3], ['Ultra2', 'Max2', 3], ['Ultra3', 'Max3', 3]]
string = "\n".join([str(item) for sublist in lst for item in sublist])
print(string)

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