Reputation: 123
I want to make sure argument passed as list has distinct values and comma separated otherwise throw error for any other delimiter like tab, space , semi colon anything.
Case 1-
input -> ['2015-01-01', '2015-02-01', '2015-02-01','2015-03-01']
output -> ['2015-01-01', '2015-02-01','2015-03-01']
Case 2-
input -> ['2015-01-01';'2015-02-01';'2015-02-01';'2015-03-01']
output -> raise exception - please enter comma separated list.
Upvotes: 0
Views: 934
Reputation: 8273
I am just assuming the expected outcome and input from the comments and answers posted earlier
import re
string_list = ["['2015-01-01';'2015-02-01';'2015-02-01';'2015-03-01']",
"['2015-01-01';'2015-02-01' '2015-02-01';'2015-03-01']",
"['2015-01-01';'2015-02-01' '2015-02-01';'2015-03-01']",
"['2015-01-01','2015-02-01','2015-02-01','2015-03-01']"
]
for i in string_list:
if re.findall(r"\d{4}-\d{2}-\d{2}'[;*&\t\s]{1,}",i):
print('invalid') # raise excpetion here
else:
print(set(i[1:-1].replace("'",'').split(',')))
Output:
invalid
invalid
invalid
set(['2015-03-01', '2015-01-01', '2015-02-01'])
The valid output would be of type set which can be converted to list if required using list()
Upvotes: 0
Reputation: 1680
Something along these lines could cleanup user input, but it will always have the potential for someone to put something unexpected in.
I would take each value separately and append them to a list, myself.
inList = "['2015-01-01';'2015-02-01';'2015-02-01';'2015-03-01']"
delimiters = [",", ";", "\t", "\n", " "]
rem = ["[", "]", '"', "'", " "]
out = []
for delimiter in delimiters:
if delimiter in inList:
for r in rem:
if delimiter == r :break
inList = inList.replace(r, '')
out = inList.split(delimiter)
break
print(out)
Upvotes: 0
Reputation: 2037
Since there is little information to go on. Here is a simple solution to what i think it is you are trying to ask:
l1 = []
while True:
user_ = input("> ")
if user_ == "exit":
break
if user_ in l1:
print("already exists")
if user_ not in l1:
l1.append(user_)
print(l1)
print(l1)
Basically this will prevent the user from inputting the same thing twice. You do not need to worry about the list being in an incorrect format. Lists in python will always have comma separation when user inputs.
If you would like to make sure the user is inputting string in a specific format IE in date form yyyy/mm/dd. You would just need to add another conditional to check that. Hope this helps.
Upvotes: 1