How to remove extra space from output list? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: How to remove extra space from output list? (/thread-37136.html) |
How to remove extra space from output list? - longmen - May-05-2022 Hi, I have this input P (0, 2,+1) (2, 0, -1) (0, 4,+1) (4, 0, -1)and I would like to have it printed out this way [(0, 2, 1), (2, 0, -1), (0, 4, 1), (4, 0, -1)]. However, due to the extra space in the input I ran into this error. Without making any change to the input, I wonder if anyone could advise? Thanks algorithm_type_2 = list(eval(user_input_2)) File "<string>", line 1 (0,,2,+1),(2,,0,,-1),(0,,4,+1),(4,,0,,-1) ^ SyntaxError: invalid syntax user_input = input().split() # input_list = user_input.split() # algorithm_type = 'X' algorithm_type = user_input.pop(0) user_input_2 = ','.join(user_input) algorithm_type_2 = list(eval(user_input_2)) print(user_input_2) print(algorithm_type_2) RE: How to remove extra space from output list? - deanhystad - May-05-2022 Looks like you want to replace ") (" with "), (". That is not a very robust way of processing input, but it will work for your specific case. RE: How to remove extra space from output list? - ibreeden - May-05-2022 Deanhystad is right, it is not a very robust way of processing input. But if you can be sure the first letter is followed by a space you can use split() to isolate this first letter. But you must use parameter "maxsplit=1" to prevent it to also split the rest of your input. user_input = "P (0, 2,+1) (2, 0, -1) (0, 4,+1) (4, 0, -1)".split(maxsplit=1) print(user_input) Then you have a list of two strings. You can pop the first element to "algorithm_type" as you did and then you have a list of one string for further processing.You need to identify the parts of the string between parentheses. You can use "re" (regular expressions) to isolate these parts. Regular expressions are not easy to read so I will explain the pattern you need. r"(\(.*?\))"
import re x = re.findall(r"\(.*?\)", "(0, 2,+1) (2, 0, -1) (0, 4,+1) (4, 0, -1)") print(x) So you get a list of strings. If you are sure the strings contain tuples, you can use eval() to make tuples of the strings, like you did.algorithm_type_2 = [] for y in x: algorithm_type_2.append(eval(y)) print(algorithm_type_2)
RE: How to remove extra space from output list? - longmen - May-05-2022 Thank you. That answers my question. (May-05-2022, 10:21 AM)ibreeden Wrote: Deanhystad is right, it is not a very robust way of processing input. But if you can be sure the first letter is followed by a space you can use split() to isolate this first letter. But you must use parameter "maxsplit=1" to prevent it to also split the rest of your input. |