Strange output - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Strange output (/thread-26653.html) |
Strange output - kintarowonders - May-08-2020 I am writing a method and it outputs unexpected results. It is supposed to break up some strings and create lists from them. Yet the lists don't contain everything I expected. Here is my code: def get_group_users(): f = open('group.example', 'r') #f is file users = [] #obvious for l in f: g = l.split(':') #g is group if (g[0] == "users"): for ul in g[3]: #ul is userline gu = ul.split(',') #gu is groupuser for u in gu: #u is user users.append(u) return usersThis is the group.example file... users:x:100:kintaro,john,autossh,test portage:x:250:portageThis is the output which I did not expect... >>> import shadowssh >>> shadowssh.get_group_users() ['k', 'i', 'n', 't', 'a', 'r', 'o', '', '', 'j', 'o', 'h', 'n', '', '', 'a', 'u', 't', 'o', 's', 's', 'h', '', '', 't', 'e', 's', 't', '\n']The output I want... ['kintaro', 'john', 'autossh', 'test'] RE: Strange output - buran - May-08-2020 replace lines 8 to 11 with users.extend(g[3].split(','))as a side note - using one-letter names is bad, use descriptive names RE: Strange output - kintarowonders - May-08-2020 That did not work, and line 8 is an important conditional so that it avoids the group portage in my example. RE: Strange output - bowlofred - May-08-2020 At line 7 your group is parsed into g as a list of strings such as ['users', 'x', '100', 'kintaro,john,autossh,test'] Line 8 is for ul in g[3]: #ul is userlineThis sets ul to the elements of g[3] one at a time. Since g[3] is a string, it sets ul to each of the characters. You want to split g[3], not loop on it. RE: Strange output - kintarowonders - May-08-2020 Thanks for helping me figure that out... def get_group_users(): f = open('group.example', 'r') users = [] for l in f: g = l.split(':') if (g[0] == "users"): for u in g[3].split(','): users.append(u) return users RE: Strange output - buran - May-08-2020 line 8 is the root of your problem g[3] is a string and you iterate over string. so u is each char in that string. then you try to split single char at ',' (line 9) what i suggest: def get_group_users(): f = open('group.example', 'r') #f is file users = [] #obvious for l in f: g = l.strip().split(':') #g is group if (g[0] == "users"): users.extend(g[3].split(',')) return users print(get_group_users()) Now, what I would do, to make better codedef get_group_users(file_name): users = [] with open(file_name, 'r') as f: for line in f: if line.startswith('users'): *_, group_users = line.strip().split(':') users.extend(group_users.split(',')) return users print(get_group_users('group.example'))
RE: Strange output - buran - May-08-2020 note the use of strip() in order to remove the new-line '\n' at the end of last element
|