May-05-2022, 11:04 PM
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.
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.
Output:['P', '(0, 2,+1) (2, 0, -1) (0, 4,+1) (4, 0, -1)']
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"(\(.*?\))"
- r"..." : pattern must be treated as a raw string.
- (..) : the parentheses capture the string that you need.
- \(...\) : search for a string inside parentheses. These parentheses must be escaped by backslashes or else they will be interpreted as capturing parentheses.
- . : dot means: match any character.
- * : asterisk means: previous character (the dot) repeated zero or more times.
- ? : question mark means: do a non-greedy (reluctant) match, so match the closest pair of parentheses. (Or else everything from the first "(" to the last ")" is captured as one string.)
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.
Output:['(0, 2,+1)', '(2, 0, -1)', '(0, 4,+1)', '(4, 0, -1)']
algorithm_type_2 = [] for y in x: algorithm_type_2.append(eval(y)) print(algorithm_type_2)
Output:[(0, 2, 1), (2, 0, -1), (0, 4, 1), (4, 0, -1)]