I have a list of string values that represents the id.age of some users:
users = ["1.20", "2.35", "3", "4", "5.", "6.30", "7."]
How can I properly split it to get the id and age separately?
Note that we have some data with the age information missing (e.g. "3" and "4"), and even worse, we have some data only with an id and a point (e.g. "5." and "7.").
Sure I can use the split function, for example:
>>> "1.2".split('.')
['1', '2']
>>> "2".split('.')
['2']
>>> "3.".split('.')
['3', '']
But, then I will need to check each result. Maybe, something like this:
res = "3.".split('.')
id = int(res[0])
if len(res) > 1:
if res[1] != "":
age = int(res[1])
Another option is to use the rpartition function, for example:
>>> "1.2".rpartition('.')
('1', '.', '2')
>>> "2".rpartition('.')
('', '', '2')
>>> "3.".rpartition('.')
('3', '.', '')
But I still need to check the results 'manually' and, in the second example, the value that should be the id is in the age position. (e.g. ('', '', '2')).
Is there a built in function that I can get the result like this?
>>> "1.2".some_split_function('.')
('1', '.', '2')
>>> "2".some_split_function('.')
('2', None, None)
>>> "3.".some_split_function('.')
('3', '.', None)
So I can just call it in a loop like this:
for user_info in users:
id, _, age = user_info.some_split_function('.')
print int(id)
if age is not None:
print int(age)